C#指定图片添加文字——修改版
程序员文章站
2022-07-16 19:35:50
...
首先引入System.Drawing.dll,链接:http://pan.baidu.com/s/1pKCU4uZ 密码:gqj6
using UnityEngine;
using System.IO;
using System.Drawing;
using Color = System.Drawing.Color;
using FontStyle = System.Drawing.FontStyle;
using Graphics = System.Drawing.Graphics;
public class AddWordToImage : MonoBehaviour
{
private string filePath;
private string savePath;
void Start()
{
filePath = Application.streamingAssetsPath + "/TX.jpg";
savePath = Application.streamingAssetsPath + "/TX1.jpg";
AddTextToImage("小鬼当家");
}
private void AddTextToImage(string text)
{
if (!File.Exists(filePath))
throw new FileNotFoundException("文件不存在");
if (string.IsNullOrEmpty(text))
return;
Image image = Image.FromFile(filePath);
Debug.Log(image.Width + " " + image.Height);
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 50f;
float textWidth = text.Length*fontSize;
System.Drawing.Font font = new System.Drawing.Font("加粗", fontSize, FontStyle.Bold);
//字体矩形位置 :
//x = 图片的长度的中心位置 - 字体长度的一半 - 字行距
//y = 图片的高度的中心位置 - 字体大小的一半 - 偏移(去掉偏移,是居中位置)
float rectX = image.Width/2 - textWidth/2 - font.Height;
float rectY = image.Height/2 - fontSize/2 - 30;
float rectWidth = text.Length*fontSize + font.Height *2;
//英文字体的1磅,相当于1/72
//英寸常用的1024x768或800x600等标准的分辨率计算出来的dpi是一个常数:96
//因此计算出来的毫米与像素的关系也约等于一个常数: 基本上 1毫米 约等于 3.78像素
float rectHeight = (fontSize/72)*96;
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
Brush whiteBrush = new SolidBrush(Color.White);
Brush blackBrush = new SolidBrush(Color.Black);
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
g.DrawString(text, font, whiteBrush, textArea);
bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
}
效果对比
上一篇: Qt获取IP地址、MAC地址等网卡信息,区分本地网卡、无线网卡和虚拟网卡
下一篇: 复合数据类型