将矩阵平移到中心并适合矩形
Translate matrix to center and fit a rectangle
我使用 SkiaSharp
在 SKCanvas
上绘制一些 SKRect。我正在尝试为绘图区域实现 "scale to fit and center" 功能。我使用以下代码计算所有 SKRect
s.
的边界框
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 中的导航器视图,正在执行我正在尝试构建的内容。
我终于找到了问题的解决方案,我想分享我的代码以帮助可能遇到类似问题的其他人。
以下方法计算矩阵的比例以适合视口。比例因子和视口矩形的平移都应用于矩阵。完成此操作后,需要重绘 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;
}
我使用 SkiaSharp
在 SKCanvas
上绘制一些 SKRect。我正在尝试为绘图区域实现 "scale to fit and center" 功能。我使用以下代码计算所有 SKRect
s.
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 中的导航器视图,正在执行我正在尝试构建的内容。
我终于找到了问题的解决方案,我想分享我的代码以帮助可能遇到类似问题的其他人。 以下方法计算矩阵的比例以适合视口。比例因子和视口矩形的平移都应用于矩阵。完成此操作后,需要重绘 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;
}