在SkiaSharp中绘制旋转的文本 [英] Draw rotated text in SkiaSharp

查看:523
本文介绍了在SkiaSharp中绘制旋转的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在SkiaSharp中绘制旋转的文本.

How to draw rotated text in SkiaSharp.

当前,我正在旋转SKCanvas,绘制文本,然后将其旋转回去.但是我认为可能有一种更有效的方法.

Currently I'm rotating the SKCanvas, drawing the text and then rotating it back. But I thought may be there is a more efficient way to do this.

   canvas.RotateDegrees(45, 20, 20);
   canvas.DrawText("Text", 20, 20, paint);
   canvas.RotateDegrees(-45, 20, 20);

推荐答案

那是正确的方法(我认为这是唯一的方法).

That is the correct way (the only way, I think).

这并不是效率不高,因为您并没有真正旋转画布,而是调整了绘图矩阵(一个int[9]数组).在引擎盖下它正在做这样的事情:

It is not that inefficient as you are not really rotating the canvas, but rather adjusting the drawing matrix (an int[9] array). Under the hood it is doing something like this:

var m = SKMatrix.CreateRotation(45); // simple struct over int[9]
canvas.CurrentMatrix.Concat(m)       // simple multiplication

然后在绘制时,它仅使用矩阵:

and then when you draw, it it just uses the matrix:

canvas.DrawText(text, matrix);

当您旋转回去时,它会再次进行数学运算.

and when you rotate back, it just does the math again.

另一种方法是保存画布,然后还原:

Another way is to save the canvas and then restore:

canvas.Save();
canvas.Rotate(45);
canvas.DrawText(text);
canvas.Restore();

这只是在保存期间复制当前矩阵.而当您还原时,它只会还原它.这是一种更好"的方式,因为您可以进行一系列转换而不必撤消.

This just makes a copy of the current matrix during the save. And when you restore, it just reverts it. This is a "better" way in that you can possible do a series of transformations, without having to reverse.

或者,您可以使用一种便利类型:

Or, you can make use of a convenience type:

// auto save
using (new SKAutoCanvasRestore(canvas)) {
    // do any transformations
    canvas.Rotate(45);
    // do serious work
    canvas.DrawText(text);
    // auto restore, even on exceptions or errors
}

另一种完全不同的绘制文本的方法是沿着路径绘制:

Another, totally different way to draw text, is to draw along a path:

var path = new SKPath();
// create path ...

// draw using path
canvas.DrawText("text", path, hOffset: 0, vOffset: 0, paint);

这篇关于在SkiaSharp中绘制旋转的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆