在
IDrawable Drawable
的MAUI.GraphicsView
属性中,我想绘制图像的一部分。这是原始图像的子矩形。
问题:我找不到方法,也找不到裁剪
IImage
返回的 PlatformImage.FromStream(stream)
的方法,也找不到只绘制 IImage
的一部分,使用类似 Skiasharp 的函数,但对于 Maui.GraphicsView
:
public void DrawImage(SkiaSharp.SKImage image, SkiaSharp.SKRect source, SkiaSharp.SKRect dest);
有人可以提出一种方法来实现这一目标吗?
为了扩展,这是我要扩展的代码:
public class GraphicsDrawable : IDrawable
{
public double Scale { get; set; }
public Point Center { get; set; }
public Rect DisplayedRect { get; set; }
private Microsoft.Maui.Graphics.IImage image;
public GraphicsDrawable()
{
// Load image
Assembly assembly = GetType().GetTypeInfo().Assembly;
using (Stream stream = assembly.GetManifestResourceStream("BOBMaui.Resources.Images.bobstart.jpg"))
{
image = PlatformImage.FromStream(stream);
}
}
public void Draw(ICanvas canvas, RectF containerRect)
{
if (image != null)
{
// Anyway, the output will be displayed on containerRect size which is the full size of the container
// STEP 1 - Computes the clipping to apply to image
// Computes scaled size which is the size of the part of the image to be displayed
double scaledWidth = image.Width / Scale;
double scaledHeight = image.Height / Scale;
// Computes horizontal coordinates
double xCenterImageOUT = Center.X * image.Width;
double xLeft = Math.Max(0, xCenterImageOUT - scaledWidth/2); // May not be negative
double xRight = Math.Min(xCenterImageOUT + scaledWidth / 2, image.Width); // May not extend outside base image
if (xRight - xLeft < scaledWidth)
{
// One of the border was forced to 0 or image.Width
if (xLeft == 0) xRight = scaledWidth;
else xLeft = image.Width - scaledWidth;
}
// Computes vertical coordinates
double yCenterImageOUT = Center.Y * image.Height;
double yTop = Math.Max(0, yCenterImageOUT - scaledHeight / 2); // May not be negative
double yBottom = Math.Min(yCenterImageOUT + scaledHeight / 2, image.Height); // May not extend outside base image
if (yBottom - yTop < scaledHeight)
{
// One of the border was forced to 0 or image.Width
if (yTop == 0) yBottom = scaledHeight;
else yBottom = image.Height - scaledHeight;
}
// Define clipping rectangle
DisplayedRect = new Rect(xLeft, yTop, scaledWidth, scaledHeight);
// STEP 2 - Paint the canvas
// There is the problem - I need to crop the image before drawing it
// Sthg like: canvas.DrawImage(image, source: DisplayRect, dest: containerRect);
canvas.DrawImage(image, containerRect.X, containerRect.Y, containerRect.Width, containerRect.Height);
}
}
}
在毛伊岛,您可以使用
Clip
属性在毛伊岛裁剪图像。
例如,您可以使用以下代码来裁剪图像:
var clip1 = new RectangleGeometry(new Rect(100, 100, 100, 100));
image.Clip = clip1;
请参阅带有几何图形的剪辑以获取更多详细信息。
您也可以查看