我使用 SkiaSharp
在 SKCanvas
上绘制一些 SKRect。我正在尝试为绘图区域实现“缩放以适合并居中”功能。我使用以下代码来计算所有 SKRect
的边界框。
private SKRect GetBoundingBox()
{
int xMin = AllRectangles.Min(s => (int)s.Left);
int yMin = AllRectangles.Min(s => (int)s.Top);
int xMax = AllRectangles.Max(s => (int)s.Right);
int yMax = AllRectangles.Max(s => (int)s.Bottom);
SKRect result = new SKRect(xMin, yMin, xMax, yMax);
return result;
}
现在我想转换 PaintSurface 期间使用的 SKMatrix
以使边界框(包含其中的所有项目)居中,并缩放边界框以适合 SKCanvasView
。我有一个 GIF,它显示了 Photoshop 中的导航器 View ,正在执行我想要构建的操作。
最佳答案
我终于找到了问题的解决方案,我想分享我的代码,以帮助其他可能遇到类似问题的人。 以下方法计算矩阵的比例以适合视口(viewport)。视口(viewport)矩形的比例因子和平移都应用于矩阵。执行此操作后,需要重新绘制 Canvas 。
public void CenterAndFitRectangle(SKRect viewport)
{
var viewPortRectangle = _currentMatrix.MapRect(viewport);
var scale = Math.Min(CanvasView.Bounds.Width / viewPortRectangle.Width, CanvasView.Bounds.Height / viewPortRectangle.Height);
_currentMatrix.ScaleX = scale;
_currentMatrix.ScaleY = scale;
_currentMatrix.TransX = -viewPortRectangle.Left * scale;
_currentMatrix.TransY = -viewPortRectangle.Top * scale;
}
关于xamarin - 将矩阵平移到中心并拟合矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026059/