2013-01-23 37 views
6

निम्नलिखित कोड वर्तमान स्क्रीन के UIImage मिलती है:कैसे वर्तमान स्क्रीन ios में एक विशिष्ट क्षेत्र के UIImage प्राप्त करने के लिए

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

अगर मैं एक CGRect रेक्ट है और मैं केवल वर्तमान स्क्रीन के UIImage प्राप्त करना चाहते हैं उस आयत में, मैं कैसे कर सकता हूं?

उत्तर

14

के लिए जाओ रेक्ट (फसल) छवि: निम्न विधि

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

0

छवि है जो आप चाहते हैं दर्रा आपकी आवश्यकता के अनुसार 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

हाँ, लेकिन अगर आर्क अक्षम है और अंत में कहां है? – Dhara

+0

एआरसी CGImageRef पर लागू नहीं होता है। अंत में, मेरा मतलब है कि आप 'UIImage' वापस लौटने से पहले। – WDUK