原文: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. SpringMVC 多文件上传

    springMVC.xml 配置 <bean id="multipartResolver" class="org.springframework.web.multi ...

  2. 关于crontab中的一些小问题

    今天写了个脚本,要写进crontab做定时任务,每5分钟跑一遍.关于crontab的介绍呢,请大家移步www.baidu.com,在这里我就不仔细介绍了.可以搜索一下“每天一个Linux命令”系列文章 ...

  3. struct class 内存结构初探-内存模型顺序和变量的实际添加顺序一致

    typedef struct structTest { char xchar; int xint; int yint; }xStruct; @interface ViewController () { ...

  4. BZOJ4321:queue2(DP)

    Description n 个沙茶,被编号 1~n.排完队之后,每个沙茶希望,自己的相邻的两人只要无一个人的编号和自己的编号相差为 1(+1 或-1)就行.现在想知道,存在多少方案满足沙茶们如此不苛刻 ...

  5. gluoncv,faster rcnn 处理难样本

    难样本,是我们在标注的时候,连肉眼都看不清的小像素物体,也可以说是既不是正样本,也不是负样本. 利用gluoncv时,这些标注框也实在存在,gluoncv会实在将他当做一个GT,但我们知道这是不好的. ...

  6. vim在插入模式粘贴代码缩进问题解决方法

    转载自:https://blog.csdn.net/commshare/article/details/6215088 在vim粘贴代码会出现缩进问题,原因在于vim在代码粘贴时会自动缩进 解决方法: ...

  7. Hadoop学习之路(十九)MapReduce框架排序

    流量统计项目案例 样本示例 需求 1. 统计每一个用户(手机号)所耗费的总上行流量.总下行流量,总流量 2. 得出上题结果的基础之上再加一个需求:将统计结果按照总流量倒序排序 3. 将流量汇总统计结果 ...

  8. HDU 1176 免费馅饼 (类似数字三角形的题,很经典,值得仔细理解的dp思维)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1176 免费馅饼 Time Limit: 2000/1000 MS (Java/Others)     ...

  9. HBase可靠性管理方法浅析

    HBase是一个可以进行实时读和写操作的分布式NoSQL系统,建立在HDFS之上,是Hadoop生态圈中重要的一部分.在HBase中底层存储结构采用的LSM-tree的方式进行处理,为了保证HBase ...

  10. Notes 20180311 : String第三讲_深入了解String

    很多前辈我可能对于我的这节文章很困惑,觉得String这个东西还有什么需要特别了解的吗?其实不然,String是一个使用十分频繁的工具类,不可避免地我们也会遇到一些陷阱,深入了解String对于我们避 ...