如何在iPhone SDK中裁剪图像?

时间:2010-06-11 15:44:08

标签: iphone

我想允许用户选择屏幕上的像素,并根据创建的像素创建新图像。是否有一个特定的课程,或者我需要自己完成这个?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分: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);

}