dotnetcore/dotnet6 使用SkiaSharp进行文字和图片拼接

引入SkiaSharp的nuget包,注意,如果项目运行到docker里,需要安装SkiaSharp.NativeAssets.Linux.NoDependencies

//画文字
public static SKImage CreateSKImage(string code)
        {
            var paint = new SKPaint
            {
                TextSize = 20f,
                IsAntialias = true,
                Color = SKColor.Parse("#FFFFFF"),
                Typeface = SKTypeface.FromFamilyName("Calibri"),
                TextAlign = SKTextAlign.Center
            };
            var size = new SKRect();
            var textWidth = paint.MeasureText(code, ref size);
            
            //根据文字样式计算画布宽度
            var bmp = new SKBitmap(Convert.ToInt32(textWidth) + 10, 40);
            using (var canvas = new SKCanvas(bmp))
            {
                canvas.DrawColor(SKColor.Parse("#E53935"));
                canvas.DrawText(code, (Convert.ToInt32(textWidth) + 10) / 2f, 25.0f, paint);
                return SKImage.FromBitmap(bmp);
            }
        }

 

//拼接图片
public static SKImage JoinSKImage(List<SKImage> images)
        {
            int maxX = 0, maxY = 0;
            foreach (var item in images)
            {
                maxX += item.Width;
                if (maxY < item.Height)
                {
                    maxY = item.Height;
                }
            }

            var bmp = new SKBitmap(maxX, maxY);
            using (var canvas = new SKCanvas(bmp))
            {
                var currentWidth = 0;
                foreach(var image in images)
                {
                    canvas.DrawImage(image, currentWidth, 0);
                    currentWidth+=image.Width;
                }
            }
            return SKImage.FromBitmap(bmp);
        }

 

posted @ 2022-02-17 11:53  along_bro  阅读(1056)  评论(0编辑  收藏  举报