如何在当前屏幕的ios获得特定区域的UIImage

问题描述:

下面的代码获得UIImage的当前屏幕:如何在当前屏幕的ios获得特定区域的UIImage

UIGraphicsBeginImageContext(self.view.frame.size); 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    [self.view.layer renderInContext:ctx]; 
    UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

如果我有一个的CGRect正确,而且我只想得到当前屏幕的UIImage在那里,我该怎么办?

对于获取矩形(裁剪)图片:

UIImage *croppedImg = nil; 
CGRect cropRect = CGRectMake(AS You Need); 
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect]; 

使用下面的方法(只要你想图像的大小)返回UIImage

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect 
    { 
     //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15); 

     CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect); 
     UIImage *cropped = [UIImage imageWithCGImage:imageRef]; 
     CGImageRelease(imageRef); 

     return cropped; 
    } 
+2

工作!我想投票表示感谢,但我没有足够的声望。 – grandagile

传递其所需的图像按照您的要求修剪并更改image.size.width和image.size.height

-(UIImage *)cropSquareImage:(UIImage *)image 
{ 
    CGRect cropRect; 

    if (image.size.width < image.size.height) 
    { 
     float x = 0; 
     float y = (image.size.height/2) - (image.size.width/2); 

     cropRect = CGRectMake(x, y, image.size.width, image.size.width); 
    } 
    else 
    { 
     float x = (image.size.width/2) - (image.size.height/2); 
     float y = 0; 

     cropRect = CGRectMake(x, y, image.size.height, image.size.height); 
    } 


    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect); 
    return [UIImage imageWithCGImage:imageRef]; 


} 
+0

你的'imageRef'会泄漏内存,你需要'CGImageRelease(imageRef);'在结尾 – WDUK

+0

是的,但是如果arc被禁用,并且在最后? – Dhara

+0

ARC不适用于CGImageRef。最后,我的意思是在你返回'UIImage'之前。 – WDUK