Dorababu Dodda
Dorababu Dodda

Reputation: 452

How to Crop image in monotouch Xamarin

I am displaying image in UIImageview and I want to crop the image, following is my requirement.

Selecting the crop icon should displays a fixed size (600X600) square that is fixed over the image with grid lines to assist in straightening the image. There will be a control that allows the image to be turned under the grid.

Upvotes: 2

Views: 2431

Answers (2)

Gandalf458
Gandalf458

Reputation: 2269

This is what I ended up using to center crop the image.

//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;
}

Upvotes: 2

Magicbjørn
Magicbjørn

Reputation: 619

You could try to make an overlaying rectangle to specify what you want to crop. Supplying an x and y (if your image is not located in the above-left corner. If it is, these values will both be 0), the width and height (for your example, they should both be 600). I don't know a method to allow grid lines to straighten the image. I don't know a method of rotating an image either. But for straight images, you could use a method that looks something like this:

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;
} 

Upvotes: 0

Related Questions