# 这是什么
ImageSharp 为 C# 第三方绘图库,在.net core 时代开创了跨平台之后,gdi + 作为仅能在 Windows 平台使用的绘图库,失去了广泛性,为了跨平台,绘图需要使用一个第三库。
# 特性
- 跨平台
- 能够读取绘制大部分图片格式
- 暂不支持 Webp 的动图格式
- 相较于 GDI + 而言,占用内存更多、绘制速度更慢
- 特殊字符绘制会出现问题,需要独立处理特殊 Unicode 或者 Emoji 字符
- 提供自动换行的文本绘制方法
# 代码示例
# 新建空白画布
1 2
| using Image<Rgba32> background = new(width, height, Color.White);
|
# 从文件读取图片
1
| Image img = Image.Load(path);
|
# 使用 rgb 新建颜色
1 2
| Color color = new Rgba32(244, 245, 247, 255);
|
# 使用 16 进制文本创建颜色
1
| Color color = Color.ParseHex("#66ccff");
|
# 变更图片大小、裁剪
1 2 3 4 5 6 7
| using Image<Rgba32> img = new(width, height, Color.White); Size size = new(48);
img.Mutate(x => x.Resize(size));
img.Mutate(x => x.Crop(width, height);
|
# 定义形状、填充颜色
1 2 3 4 5 6 7 8
| IPath container = new RectangularPolygon(X, Y, width, height);
img.Fill(new Rgba32(244, 245, 247), container);
|
# 绘制圆形图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| using Image<Rgba32> background = new(width, height, Color.White); Size avatarSize = new(48); using Image avatar = Image.Load("sample path");
avatar.Mutate(x => x.Resize(avatarSize));
using Image<Rgba32> avatarFrame = new(48, 48, new Rgba32(255, 255, 255, 0));
IPath circle = new EllipsePolygon(avatarFrame.Width / 2, avatarFrame.Height / 2, avatarFrame.Width / 2);
avatarFrame.Mutate(x => x.Fill(new ImageBrush(avatar), circle));
background.Mutate(x => x.DrawImage(avatarFrame, new Point(14, 14), 1));
|
# 将图片绘制在另一张图片中
1 2 3
| background.Mutate(x => x.DrawImage(avatarFrame, new Point(14, 14), 1));
|
# 自定义绘制流程函数
1 2 3 4 5 6 7
| private IImageProcessingContext RenderRichText(Item item, IImageProcessingContext img) { return img; } background.Mutate(x => RenderRichText(item, x));
|
# 文本绘制、文本长度高度测量
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Font bigFont = SystemFonts.CreateFont("Microsoft YaHei", 20);
TextOptions option = new TextOptions(bigFont) { TextAlignment = TextAlignment.Start, VerticalAlignment = VerticalAlignment.Center, WrappingLength = 100, Origin = new Point(10, 10) };
Info.Mutate(x=>x.DrawText(Name, smallFont, Color.Black));
var size = TextMeasurer.Measure(Name, option);
|