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();
    }
}

 

效果对比

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值