如何在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);
}