天天看點

C#指定圖檔添加文字——修改版

首先引入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();
    }
}
           

效果對比

C#指定圖檔添加文字——修改版
C#指定圖檔添加文字——修改版