从中心向外裁剪UIImage?

时间:2009-12-13 01:25:54

标签: iphone uiimage zoom center crop

我正在制作包含数码变焦的相机应用程序。我有一个滑块(zoomSlider),其最小值为1,最大值为4.当用户点击相机按钮时,它会拍照,然后我将其裁剪为缩放。我有两个问题:

如何裁剪图像的中间位置? (例如,2倍变焦,矩形将以600x800的尺寸为中心(适用于iPhone 2G / 3G))

当我这样做时,它会旋转图像。我通过旋转UIImageView来弥补它,但这会导致人像变成风景,反之亦然。

这是我的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

     if ([mediaType isEqualToString:@"public.image"]){

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

          CGRect clippedRect = CGRectMake(600, 450, image.size.width/zoomSlider.value, image.size.height/zoomSlider.value);

          UIImage *cropped = [self imageByCropping:image toRect:clippedRect];

          CGRect croppedImageSize = CGRectMake(0, 0, image.size.width/zoomSlider.value, image.size.height/zoomSlider.value);

          [cropped drawInRect:croppedImageSize];

          zoomPhoto.frame = croppedImageSize;

          zoomPhoto.image = cropped;

CGAffineTransform rotateTransform = CGAffineTransformRotate(CGAffineTransformIdentity,

                                                                                     RADIANS(90.0));

          zoomPhoto.transform = rotateTransform;
}

- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect

{

     CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);



     UIImage *cropped = [UIImage imageWithCGImage:imageRef];

CGImageRelease(imageRef);




 return cropped;

}

1 个答案:

答案 0 :(得分:1)

CGFloat newWidth = image.size.width/zoomSlider.value;
CGFloat newHeight = image.size.height/zoomSlider.value;

CGRect clippedRect = CGRectMake((image.size.width-newWidth)/2, (image.size.height-newHeight)/2, newWidth, newHeight);

删除它以不旋转图像:

CGAffineTransform rotateTransform = CGAffineTransformRotate(CGAffineTransformIdentity,RADIANS(90.0));

zoomPhoto.transform = rotateTransform;