开发者

How to crop images in iPhone SDK?

I want to allow a user to select pixels on the screen and crea开发者_如何学JAVAte a new image from the pixels created. Is there a specific class for this or would I need to do this all my self?


you should have a look at http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/


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

}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜