2013-01-23 7 views
6

Il codice seguente ottiene UIImage della schermata corrente:Come ottenere UIImage di una specifica area in ios attuale dello schermo

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

Se ho un rettangolo CGRect e voglio ottenere solo l'UIImage della schermata corrente in quel modo, come posso fare?

risposta

14

per Get Rect (Crop) Image:

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

Usa seguente metodo che restituiscono UIImage (come si desidera dimensione dell'immagine)

- (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

Questo funziona! Voglio votare per ringraziare, ma non ho abbastanza reputazione. – grandagile

0

Far passare l'immagine che si desidera da ritagliare e modificare image.size.width e image.size.height secondo le vostre esigenze

-(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

Il tuo 'imageRef' sta per perdere memoria, hai bisogno di' CGImageRelease (imageRef); 'alla fine – WDUK

+0

sì ma se l'arco è disabilitato e dove alla fine? – Dhara

+0

ARC non si applica a CGImageRef. Alla fine, voglio dire prima di restituire "UIImmagine". – WDUK

Problemi correlati