2010-06-11 7 views
1

Je souhaite autoriser un utilisateur à sélectionner des pixels sur l'écran et créer une nouvelle image à partir des pixels créés. Y a-t-il une classe spécifique pour cela ou est-ce que je devrais le faire tout seul?Comment rogner des images dans iPhone SDK?

Répondre

1
- (UIImage*)getCroppedImage  
{ 
CGRect rect = self.cropView.frame; 
CGRect drawRect = [self cropRectForFrame:rect]; 
UIImage *croppedImage = [self imageByCropping:self.image toRect:drawRect];  
return croppedImage; 
} 

- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect 
{  
     if (UIGraphicsBeginImageContextWithOptions) 
{ 
     UIGraphicsBeginImageContextWithOptions(rect.size, 
              /* opaque */ NO, 
              /* scaling factor */ 0.0); 
} 
else 
{ 
     UIGraphicsBeginImageContext(rect.size); 
} 

// stick to methods on UIImage so that orientation etc. are automatically 
// dealt with for us 
[image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)]; 

UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return result; 

}

-(CGRect)cropRectForFrame:(CGRect)frame 
{  
NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit"); 

CGFloat widthScale = self.bounds.size.width/self.image.size.width; 
CGFloat heightScale = self.bounds.size.height/self.image.size.height; 

float x, y, w, h, offset; 
if (widthScale<heightScale) { 
    offset = (self.bounds.size.height - (self.image.size.height*widthScale))/2; 
    x = frame.origin.x/widthScale; 
    y = (frame.origin.y-offset)/widthScale; 
    w = frame.size.width/widthScale; 
    h = frame.size.height/widthScale; 
} else { 
    offset = (self.bounds.size.width - (self.image.size.width*heightScale))/2; 
    x = (frame.origin.x-offset)/heightScale; 
    y = frame.origin.y/heightScale; 
    w = frame.size.width/heightScale; 
    h = frame.size.height/heightScale; 
} 
return CGRectMake(x, y, w, h); 

}

Questions connexes