如何在目标c中裁剪图像?

时间:2013-08-13 09:41:48

标签: iphone ios objective-c

用户可以更改编辑屏幕中默认显示的裁剪框大小。我尝试使用以下代码:

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

    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef); 
    return cropped;
}

但它裁剪固定区域。如何裁剪用户选择的区域?

2 个答案:

答案 0 :(得分:25)

获取裁剪图片:

UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake("AS YOu Need"); //set your rect size.
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];

使用以下代码调用 croppIngimageByImageName:toRect:方法返回UIImage(具有特定图片大小的

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
    {
        //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);

        CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
        UIImage *cropped = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);

        return cropped;
    }

答案 1 :(得分:7)

    CGRect clippedRect  = CGRectMake(0 ,0,180 ,180);
    CGImageRef imageRef = CGImageCreateWithImageInRect(imgVw1.image.CGImage, clippedRect);
    UIImage *newImage   = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    imgVw1Cliped.image=newImage;

    NSLog(@"%d",imgVw1Cliped.image.imageOrientation);