Esqarrouth
Esqarrouth

Reputation: 39201

Crop and recreate UIImage

I want to crop a UIImage (not imageview), before doing pixel operations on it. Is there a reliable way to do this in ios framework?

Here are the related methods in android I am using:

http://developer.android.com/reference/android/graphics/Bitmap.html#createBitmap(android.graphics.Bitmap, int, int, int, int) http://developer.android.com/reference/android/graphics/Bitmap.html#createBitmap(int, int, android.graphics.Bitmap.Config)

Upvotes: 0

Views: 336

Answers (3)

Esqarrouth
Esqarrouth

Reputation: 39201

This worked for me:

-(UIImage *)cropCanvas:(UImage *)input x1:(int)x1 y1:(int)y1 x2:(int)x2 y2:(int)y2{
    CGRect rect = CGRectMake(x1, y1, input.size.width-x2-x1, input.size.height-y2-y1);
    CGImageRef imageref = CGImageCreateWithImageInRect([input CGImage], rect);
    UIImage *img = [UIImage imageWithCGImage:imageref];
    return img;
}

Upvotes: 0

Amit Bhavsar
Amit Bhavsar

Reputation: 1283

-(UIImage*)scaleToSize:(CGSize)size image:(UIImage*)image
{
    UIGraphicsBeginImageContext(size);

    // Draw the scaled image in the current context
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    // Create a new image from current context
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    // Pop the current context from the stack
    UIGraphicsEndImageContext();

    // Return our new scaled image
    return scaledImage;
}

Upvotes: 6

MonsieurDart
MonsieurDart

Reputation: 6045

I would advise you to look at:

  • The CoreAnimation Apple framework to create an image context, draw in it and save this as a UIImage in RAM or save it to disk.

  • The CoreImage Apple framework if you want a powerful and fully customizable image manipulation solution.

  • A third party lib to crop and resize images: CocoaPods is a great way to quickly integrate that kind of libs… Here is a list of a some interesting image manipulation pods.

Upvotes: 0

Related Questions