如何在Monotouch Xamarin中裁剪图像

时间:2014-07-26 13:28:16

标签: c# xamarin.ios xamarin crop

我在UIImageview中显示图像,我想裁剪图像,以下是我的要求。

选择裁剪图标应显示固定尺寸(600X600)的正方形,该正方形使用网格线固定在图像上,以帮助拉直图像。将有一个控件允许图像在网格下转动。

2 个答案:

答案 0 :(得分:1)

这是我最终用来裁剪图像的中心。

//Crops an image to even width and height
public UIImage CenterCrop(UIImage originalImage)
{
    // Use smallest side length as crop square length
    double squareLength = Math.Min(originalImage.Size.Width, originalImage.Size.Height);

    nfloat x, y;
    x = (nfloat)((originalImage.Size.Width - squareLength) / 2.0);
    y = (nfloat)((originalImage.Size.Height - squareLength) / 2.0);

    //This Rect defines the coordinates to be used for the crop
    CGRect croppedRect = CGRect.FromLTRB(x, y, x + (nfloat)squareLength, y + (nfloat)squareLength);

    // Center-Crop the image
    UIGraphics.BeginImageContextWithOptions(croppedRect.Size, false, originalImage.CurrentScale);
    originalImage.Draw(new CGPoint(-croppedRect.X, -croppedRect.Y));
    UIImage croppedImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();

    return croppedImage;
}

答案 1 :(得分:0)

您可以尝试制作一个重叠的矩形来指定要裁剪的内容。提供x和y(如果你的图像不在左上角。如果是,这些值都是0),宽度和高度(例如,它们都应该是600)。我不知道允许网格线拉直图像的方法。我也不知道旋转图像的方法。但对于直接图像,您可以使用看起来像这样的方法:

private UIImage Crop(UIImage image, int x, int y, int width, int height)
{
    SizeF imgSize = image.Size;

    UIGraphics.BeginImageContext(new SizeF(width, height));
    UIGraphics imgToCrop = UIGraphics.GetCurrentContext();

    RectangleF croppingRectangle = new RectangleF(0, 0, width, height);
    imgToCrop.ClipToRect(croppingRectangle);

    RectangleF drawRectangle = new RectangleF(-x, -y, imgSize.Width, imgSize.Height);

    image.Draw(drawRectangle);
    UIGraphics croppedImg = UIGraphics.GetImageFromCurrentImageContext();

    UIGraphics.EndImageContext();
    return croppedImg;
}