将UIImage裁剪为新的宽高比

时间:2011-07-15 15:09:56

标签: iphone xcode ipad uiimage crop

我想裁剪UIImage以获得新的宽高比......

bounds是带有(0,0, newwidth, newhigh) ...

的CGRect
- (UIImage *)croppedImage:(UIImage *)myImage :(CGRect)bounds {
    CGImageRef imageRef = CGImageCreateWithImageInRect(myImage.CGImage, bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CGSize asd =  croppedImage.size;
    return croppedImage;
}

致电:

[workImage croppedImage: workImage: CGRectMake(0, 0, newWidth, newHeigh)];

之后,“workimage”与之前的尺寸相同......

可能出错?

问候

1 个答案:

答案 0 :(得分:3)

嗯,您没有改变当前图像,因为这似乎是UIImage上的类别方法。您正在创建一个新图像并将其返回。那么这将起作用,

workImage = [workImage croppedImage: workImage: CGRectMake(0, 0, newWidth, newHeigh)];

但是我认为这个方法更好地命名,(假设它是UIImage上的类别方法)

- (UIImage *)croppedImageWithRect:(CGRect)bounds {
    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CGSize asd =  croppedImage.size;
    return croppedImage;
}

这样你就可以这样称呼它,

workImage = [workImage croppedImageWithRect:CGRectMake(0, 0, newWidth, newHeigh)];

作为旁注,不要使用像croppedImage::这样的方法。最好为所有参数命名,比如说croppedImage:rect: