WPF GDI+字符串绘制成图片(二)

本章讲述:在WPF中,使用GDI+技术,把字符串数据绘制成图片;文字可分为:居左显示、居中显示、居右显示。

完整的例子参考网址:

1、XAML 前端设计

<Window x:Class="WPF_GDI_Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Border Margin="1" BorderThickness="1" BorderBrush="Gray">
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
                <Button Margin="10" Content="左对齐" Height="25" Width="50" Click="Button_Click"/>
                <Button Margin="10" Content="居中对齐" Height="25" Width="60" Click="Button_Click_1"/>
                <Button Margin="10" Content="右对齐" Height="25" Width="50" Click="Button_Click_2"/>
            </StackPanel>
        </Border>
        <Border Margin="1" BorderThickness="1" BorderBrush="Gray">
            <Image x:Name="img" />
        </Border>
    </StackPanel>
</Window>

2、后台逻辑主要代码

private List<string> SourStrs;
private string path = System.Windows.Forms.Application.StartupPath + "\\11.png";
private int mapwidth = 1920;
private int mapheight = 1080;
private float fontSize;
private string fontFamily;

public MainWindow()
{
	InitializeComponent();

	Drawing();
}

private void Drawing()
{
	fontFamily = "Microsoft YaHei";
	fontSize = 100f;
	string str1 = "一个实用的C#字符串操作类,内置了14个字符串处理函数,几乎囊括了所有常用到的字符串处理操作,比如转换字符串,获取指定字符分";
	int strlen = str1.Length;
	int num = Encoding.Default.GetBytes(str1).Length;
	Font font = new Font(fontFamily, fontSize);
	this.DrawingTextImage(str1, font, 1920, 1080);
}

private void DrawingTextImage(string txt, Font font, int w, int h)
{
	int strlen = txt.Length;
	int num = Encoding.Default.GetBytes(txt).Length;
	Bitmap map = new Bitmap(1920, 1080);
	Graphics g = Graphics.FromImage(map);
	g.PageUnit = GraphicsUnit.Pixel;
	g.SmoothingMode = SmoothingMode.HighQuality;
	g.Clear(Color.Black);
	g.DrawRectangle(new Pen(Color.Red, 4f), 10, 10, 0x76c, 0x424);
	SizeF size1 = this.Get_StrWidth1(g, "字", font);
	SizeF size2 = this.Get_StrWidth1(g, "H", font);
	int n = (int)(((float)w) / size2.Width);
	char[] txtSour = txt.ToArray<char>();
	List<string> bkstrs = this.GetStrList(g, font, txt, 1080);
	this.SourStrs = bkstrs;
	int row = 0;
	foreach (string tmp in bkstrs)
	{
		g.DrawString(tmp, font, Brushes.OrangeRed, (float)0f, (float)(row * size2.Height));
		row++;
	}
	g.Dispose();
	map.Save(this.path, System.Drawing.Imaging.ImageFormat.Png);
	map.Dispose();
	this.BitmpToImageSource(this.path);
}

//居左、居中、居右显示
private void DrawStringBitmap(int mode)
{
	Bitmap map = new Bitmap(1920, 1080);
	Graphics g = Graphics.FromImage(map);
	g.PageUnit = GraphicsUnit.Pixel;
	g.SmoothingMode = SmoothingMode.HighQuality;
	g.Clear(Color.Black);
	g.DrawRectangle(new Pen(Color.Red, 4f), 10, 10, 0x76c, 0x424);
	Font font = new Font(this.fontFamily, this.fontSize);
	float row = 0f;
	float tmph = this.Get_StrWidth1(g, "H", font).Height;
	foreach (string tmp in this.SourStrs)
	{
		SizeF size = this.Get_StrWidth1(g, tmp, font);
		float x = 0f;
		switch (mode)
		{
			case 0:
				x = 0f;
				break;

			case 1:
				x = (this.mapwidth - size.Width) / 2f;
				break;

			case 2:
				x = this.mapwidth - size.Width;
				break;
		}
		g.DrawString(tmp, font, Brushes.OrangeRed, x, row * size.Height);
		row++;
	}
	g.Dispose();
	map.Save(this.path, ImageFormat.Png);
	map.Dispose();
	this.BitmpToImageSource(this.path);
}

private double Get_StrWidth1(Graphics g, char txt, Font font)
{
	return (double)g.MeasureString(txt.ToString(), font).Width;
}

private double Get_StrWidth2(Graphics g, string txt, Font font)
{
	return (double)TextRenderer.MeasureText(g, txt, font, new System.Drawing.Size(0, 0)).Width;
}

private SizeF Get_StrWidth1(Graphics g, string txt, Font font)
{
	return TextRenderer.MeasureText(g, txt, font, new System.Drawing.Size(0, 0));
}

public static System.Windows.Media.FormattedText Get_StrWidth(string txt, double fontSize, string fontFamily)
{
	System.Windows.Media.FormattedText formattedText = new System.Windows.Media.FormattedText(
			txt,
			System.Globalization.CultureInfo.InvariantCulture,
			System.Windows.FlowDirection.LeftToRight,
				new System.Windows.Media.Typeface(fontFamily.ToString()),
				fontSize,
				System.Windows.Media.Brushes.Black
	  );

	return formattedText;
}

3、输入字符串处理逻辑

private int GetRowIndex(Graphics g, Font font, int ridex, string txt, int n, out string otxt, bool isend)
{
	int len = n;
	string tmptxt = txt.Substring(ridex, n);
	double txtw = 0.0;
	double maxw = 1920.0;
	double tmp = 0.0;
	do
	{
		tmp = this.Get_StrWidth1(g, tmptxt, font).Width;
		txtw = tmp;
		if (isend)
		{
			break;
		}
		if (txtw < maxw)
		{
			tmptxt = txt.Substring(ridex, ++len);
		}
		else
		{
			len--;
			tmptxt = tmptxt.Substring(0, len);
		}
	}
	while (txtw < maxw);
	otxt = tmptxt;
	return len;
}

private List<string> GetStrList(Graphics g, Font font, string txt, int maxh)
{
	List<string> bk = new List<string>();
	string tmptxt = null;
	int idex = 0;
	double tmph = 0.0;
	double w = 1920.0;
	SizeF size2 = this.Get_StrWidth1(g, "H", font);
	int n = (int)(w / ((double)size2.Width));
	int row = 0;
	bool isend = false;
	do
	{
		if ((idex + n) > txt.Length)
		{
			n = txt.Length - idex;
			isend = true;
		}
		idex += this.GetRowIndex(g, font, idex, txt, n, out tmptxt, isend);
		row++;
		tmph = row * size2.Height;
		if (maxh > tmph)
		{
			bk.Add(tmptxt);
		}
	}
	while (tmph < maxh);
	return bk;
}

4、保存图片

//保存图片
private void BitmpToImageSource(string filepath)
{
	System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
	byte[] buffer = new byte[fs.Length];
	fs.Read(buffer, 0, buffer.Length);
	fs.Close();
	fs.Dispose();

	System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
	System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
	bitmapImage.BeginInit();
	bitmapImage.StreamSource = ms;
	bitmapImage.EndInit();

	img.Source = bitmapImage;
}

5、按钮响应事件

private void Button_Click(object sender, RoutedEventArgs e)
{
	if (this.SourStrs != null)
	{
		DrawStringBitmap(0);//参数0:居左;1:居中;2:居右
	}
}

6、效果图

WPF(Windows Presentation Foundation)是一种用于创建用户界面的技术,而GDI(Graphics Device Interface)是一种用于绘制图形的API。在WPF中,可以使用GDI绘制图形,通过使用GDI绘制图形,我们可以实现更加定制化和高级的图形效果。 在WPF中,可以使用GDI绘制各种类型的图形,如直线、矩形、椭圆、多边形等。通过使用GDI,我们可以设置各种样式和属性,例如线条的颜色、线宽、填充颜色等,以及阴影、渐变等效果。使用GDI绘制图形的过程是通过在WPF中创建一个GDI绘图对象,然后调用其相应的方法和属性来实现绘制。 在使用GDI绘制图形时,需要注意GDI是基于像素的,因此绘制的图形会受到屏幕分辨率的影响。在WPF中,可以使用Transform矩阵类来实现图形的缩放、平移和旋转等操作,以适应不同分辨率的屏幕。 尽管WPF本身提供了丰富的图形绘制功能,但在某些情况下,使用GDI绘制图形可能会更加灵活和高效。例如,如果需要实现一些特殊的效果,如镜像、叠加等,可以使用GDI来实现。此外,如果需要与现有的GDI代码进行交互,使用GDI绘制图形也是一种不错的选择。 总之,使用WPFGDI结合绘制图形,可以实现更加丰富和高级的效果。通过使用GDI绘制图形,我们可以更好地控制图形的样式和属性,并且可以适应不同的分辨率和交互需求。这种组合使用可以使我们在图形绘制方面拥有更大的灵活性和创造力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值