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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BYH371256/article/details/83412533

本章讲述:在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 GDI+字符串绘制成图片(二)的更多相关文章

  1. WPF GDI+字符串绘制成图片(一)

    原文:WPF GDI+字符串绘制成图片(一) 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/BYH371256/article/details/83 ...

  2. C# 在网页中将Base64编码的字符串显示成图片

    在写一个接口,返回的json里面有图片,是Base64编码的字符串. 测试接口的时候,发现原来在html显示,是直接可以将Base64编码的字符串显示成图片的. 格式如下: <img src=d ...

  3. Gson字符串编码,字符串转换成图片保存,二进制转换成图片保存

    import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import ...

  4. base64字符串转化成图片

    package com.dhht.wechat.util; import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder; import ja ...

  5. c# 图片转二进制/字符串 二进制/字符串反转成图片

    protected void Button1_Click(object sender, EventArgs e) { //图片转二进制 byte[] imageByte = GetPictureDat ...

  6. C# Base64字符串转换成图片及图片转换为Base64

    最近有朋友经常会问我一些问题,例如,如何把一个字符串转换成base64字符串,如何把一个二进制文件转换成Base64文件,以及如何转换回原有的文件,在此我把方法写一下   字符串与Base64相互转换 ...

  7. python 将base64字符串还原成图片保存

    import os,base64 strs='''/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCI ...

  8. base64转换成图片

    前端代码JS: 前端图片为canvsa绘图转base64格式 function putTextInfo() { var canvasImg = painting.canvas.toDataURL('i ...

  9. java 后台将base64字符串保存为图片

    直接上代码: import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; impo ...

随机推荐

  1. java内部类之成员内部类之局部内部类

    局部内部类特点: 1.定义在代码块.方法体内的类叫局部内部类 2.局部内部类访问外部类的属性和方法使用“外部类名.this.属性名”和“外部类名.this.方法名(参数)”的形式 3.对外部世界完全隐 ...

  2. MySQL存储过程-把一个查询的结果,做为变量,更新另一张表

    create table t1(c1 varchar(20));insert into t1 select 't1'; create table t2(c2 varchar(20));insert i ...

  3. classlist和array.prototype.slice.call

    1.classlist document.getElementById("myDIV").classList.add("mystyle"); classList ...

  4. 1、Spring Cloud - 微服务简介

    前言: 业界大牛马丁.福勒(Martin Fowler) 这样描述微服务: 论文网址:https://martinfowler.com/articles/microservices.html 就目前而 ...

  5. 9、Web Service-IDEA-jaxrs 服务端客户端的实现

    关于RestFul编程可以参考:https://www.cnblogs.com/wang-yaz/p/9237981.html 关于jaxrs的实现需要有restful的理解. 话不多说直接上代码!! ...

  6. 关于IntelliJ IDEA 文档无法编辑的解决办法

    问题:在调试的时候,光标无法聚焦到代码区,导致无法编辑代码.停止调试后,问题仍然存在,需要重启idea. 这个问题纠结了我一个上午,百狗一通,发现都是说要卸载vim插件啥的,但是我是没装过vim插件. ...

  7. 快速排序及STL中的sort算法

    快速排序基本思想是,对待排序序列进行划分(Partition),一次划分,选择一个元素作为枢轴,然后将所有比枢轴小的元素放到枢轴的左边,将比枢轴大的元素放到枢轴的右边.然后对该枢轴划分的左右子序列分别 ...

  8. git删除指定文件夹

    1.在本地仓库删除指定文件 git rm 文件名名称 2.在本地仓库删除指定文件夹 git rm -r 文件夹/ 3.提交修改 git commit -m"删除文件夹" 4.推送到 ...

  9. 【postgresql的使用】

    #安装: #初始化: #允许远程登录: #创建数据库并指定用户 #创建用户 #列出数据库 #进入数据库 #查询数据 #or(或)查询 #and ,or(和,或查询) #表连接 #内,外(左右),交叉连 ...

  10. JavaScript中的this详解(彻底弄懂js中的this用法)!

    要想学好js,那么其中那些特别令人混淆迷惑的知识点,就一定要弄清楚.this关键字就是其中让初学者比较迷惑的知识点之一,不过灵活运用this可以提升代码的性能和复用性,那么今天我就和大家一起来了解th ...