DrawingVisual类是一个轻量级的绘图类,用于呈现形状、 图像或文本。它通常是在后台或者剪切板中绘制,用来生成一张图片。
这里用DrawingVisual实现类似微信对话框的效果,如图:
绘制原理:将对话框和头像绘制在一张画布上,头像大小固定为36x36像素,根据行高、文字大小等计算绘制文本的大小,再根据文本大小对原始对话框底图进行裁剪和拼接(四个角保留,对四条边进行拉伸,这样可以保留原始底图的样式)。
原对话框底图:
实现步骤:
1、首先实现绘制图片类DrawDialog.cs,添加全局变量(这些属性可根据具体情况进行调整,或者变成控件实时控制),其中的ImageHelper类参考https://blog.csdn.net/dnazhd/article/details/90257098;
public class DrawDialog
{
private static int ImageWidth = 200;//绘制整体图片的宽
private static int ImageHeight = 100;//绘制整体图片的高
private static string DialogBgPath = "";//对话框底图路径
private static BitmapImage DialogBGImage = null;//对话框底图
private static string Text = "";//对话内容
private static Size TextAreaSize = new Size(200, 100);//文本区域大小
private static int MaxTextWidth = 190;//最大文本宽度
private static int TextFontsize = 20;//字体大小
private static Color FontColor = Colors.Black;//字体颜色
private static int TextEdge = 55;//文本边距,可根据对话框底图进行调整
private static int LineSpace = 5;//文本行间距
private static string IconPath = "";//头像路径
private static BitmapImage IconImage = null;//头像
private static int IconWidth = 36;//头像宽
private static int IconHeight = 36;//头像高
private static int DialogToIconDistance = 5;//对话框距头像的距离
/// <summary>
/// 绘制对话框
/// </summary>
public static BitmapImage DrawDialogImage(string text,string iconPath,string dialogPath)
{
Text = text;
DialogBgPath = dialogPath;
IconPath = iconPath;
InitDrawParam();//初始化绘制参数
RenderTargetBitmap rtb = new RenderTargetBitmap(ImageWidth, ImageHeight, 96, 96, PixelFormats.Default);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
DrawContent(dc);//绘制对话内容
DrawIcon(dc);//绘制头像
}
rtb.Render(dv);
return ImageHelper.ConventToBitmapImage(rtb);
}
/// <summary>
/// 初始化绘制参数
/// </summary>
private static void InitDrawParam()
{
//获取头像
IconImage = ImageHelper.LoadBitmapImageUniform(IconPath, IconWidth, IconHeight);
if (IconImage == null)
{
IconWidth = IconHeight = 0;
}
//获取文本大小
if (string.IsNullOrEmpty(Text))
{
TextAreaSize = new Size(0, 0);
}
else
{
Size textSize = GetTextSize(Text);
TextAreaSize = new Size((int)Math.Round(textSize.Width), (int)Math.Round(textSize.Height));
}
//获取对话框底图
System.Drawing.Bitmap bmpDialog = (System.Drawing.Bitmap)ImageHelper.LoadImageByPath(DialogBgPath);
//获取对话框背景图
DialogBGImage = ImageSplitJoi