开发者

How to scale up and crop a UIImage?

开发者 https://www.devze.com 2023-01-14 04:45 出处:网络
Here\'s the code I have but it\'s crashing ... any ideas? UIImage *tempImage = [[UIImage alloc] initWithData:imageData];

Here's the code I have but it's crashing ... any ideas?

UIImage *tempImage = [[UIImage alloc] initWithData:imageData];
CGImageRef imgRef = [tempImage CGImage];
 [tempImage release];

 CGFloat width = CGImageGetWidth(imgRef);
 CGFloat height = CGImageGetHeight(imgRef);
 CGRect bounds = CGRectMake(0, 0, width, height);
 CGSize size = bounds.size;

 CGAffineTransform transform = CGAffineTransformMakeScale(4.0, 4.0);

 UIGraphicsBeginImageContext(size);
 CGContextRef contex开发者_开发百科t = UIGraphicsGetCurrentContext();
 CGContextConcatCTM(context, transform);
 CGContextDrawImage(context, bounds, imgRef);
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

What am I missing here? Basically just trying to scale image up and crop it to be same size as original.

Thanks


The problem is this line:

CGImageRef imgRef = [tempImage CGImage];

Or more precise, the direct follow-up of this line:

[tempImage release];

You are getting a CF object here, the CGImageRef. Core Foundation object only have the retain/release memory management, but no autoreleased objects. Hence, when you release the UIImage in the second row, the CGImageRef will be deleted as well. And this again means that it's undefined when you try to draw it down there.

I can think of three fixes:

  • use autorelease to delay the release of the image: [tempImage autorelease];
  • move the release to the very bottom of your method
  • retain and release the image using CFRetain and CFRelease.


Try this one:

-(CGImageRef)imageCapture
{
    UIGraphicsBeginImageContext(self.view.bounds.size);
   [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
   UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   CGRect rect= CGRectMake(0,0 ,320, 480);

   CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], rect);
   return imageRef;
}

use the below line whenever you want to capture the screen

UIImage *captureImg=[[UIImage alloc] initWithCGImage:[self imageCapture]];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号