如何裁剪具有特定位置的图像并设置为另一个视图

时间:2014-03-29 09:48:37

标签: ios objective-c

从特定位置裁剪图像并设置为另一个视图

最终图片视图

self.finalImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 320, 320)];
if(rectangle_button_preesed_view)
{
    self.finalImageView.image =[self croppIngimageByImageName:self.imageView.image toRect:CGRectMake(30, 120, 260, 340)];
}
else
{
    self.finalImageView.image =[self croppIngimageByImageName:self.imageView.image toRect:CGRectMake(30, 80, 260, 260)];
}

裁剪图片

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    NSLog(@" cropped size %f %f ",cropped.size.width,cropped.size.height);
    return cropped;    
}

3 个答案:

答案 0 :(得分:0)

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

OR

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)rect {

    rect = CGRectMake(rect.origin.x*self.scale, 
                      rect.origin.y*self.scale, 
                      rect.size.width*self.scale, 
                      rect.size.height*self.scale);       

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef 
                                          scale:self.scale 
                                    orientation:self.imageOrientation]; 
    CGImageRelease(imageRef);
    return result;
}

@end

答案 1 :(得分:0)

CoreGraphics解决方案外,我还建议使用支持图像处理过滤器的CoreImage。您应该查看this documentation page中找到的CICrop过滤器。

注意: iOS 5或更高版本支持此过滤器。

我目前没有确切的解决方案,但您可以继续使用a similar thread

希望它有所帮助!

答案 2 :(得分:0)

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)cropRect {

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], cropRect);
    UIImage *cropedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropedImage;

}