Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage from a region of UIView

I'm trying to clip a region of an UIView, into a UIImage for later reuse.

I've worked out this code from some snippets:

 CGRect _frameIWant = CGRectMake(100, 100, 100, 100);

 UIGraphicsBeginImageContext(view.frame.size);
 [view.layer renderInContext:UIGraphicsGetCurrentContext()];

 //STEP A: GET AN IMAGE FOR THE FULL FRAME
 UIImage *_fullFrame = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 //STEP B: CLIP THE IMAGE
 CGImageRef _regionImage = CGImageCreateWithImageInRect([_fullFrame CGImage], _frameIWant);
 UIImage *_finalImage = [UIImage imageWithCGImage:_regionImage];
 CGImageRelease(_regionImage);

'view' is the UIView which I'm clipping and _finalImage is the UIImage I want.

The code works without problem, however is kind of slow. I believe that some performance could be gained by taking just the portion of the screen directly in Step A.

I'm looking for something like renderInContext: withRect: or UIGraphicsGetImageFromCurrentImageContextWithRect() hehe.

Still haven't found anything yet :(, please help me if you know of some alternative.

like image 841
Ale Morales Avatar asked Oct 12 '10 20:10

Ale Morales


People also ask

How do I render UIView to UIImage?

extension UIView { // Using a function since `var image` might conflict with an existing variable // (like on `UIImageView`) func asImage() -> UIImage { if #available(iOS 10.0, *) { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer. image { rendererContext in layer. render(in: rendererContext.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


1 Answers

This method clips a region of the view using less memory and CPU time:

-(UIImage*)clippedImageForRect:(CGRect)clipRect inView:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(clipRect.size, YES, 1.f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, -clipRect.origin.x, -clipRect.origin.y);
    [view.layer renderInContext:ctx];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
like image 156
Felix Avatar answered Sep 30 '22 00:09

Felix