我使用以下代码从较大的 UIImage 中裁剪并创建一个新的 UIImage。我已将问题与函数 CGImageCreateWithImageInRect() 隔离开来,该函数似乎没有按照我想要的方式设置某些 CGImage 属性。 :-) 问题是调用函数 UIImagePNGRepresentation() 失败,返回 nil。
CGImageRef origRef = [stillView.image CGImage];
CGImageRef cgCrop = CGImageCreateWithImageInRect( origRef, theRect);
UIImage *imgCrop = [UIImage imageWithCGImage:cgCrop];
...
NSData *data = UIImagePNGRepresentation ( imgCrop);
-- libpng 错误:没有 IDAT 写入文件
知道从 UIImage 中裁剪出矩形可能会出现什么问题或替代方案吗?
我遇到了同样的问题,但只是在 iOS 3.2 上测试兼容性时。在 4.2 上它工作正常。
最后我发现了这个http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/这对两者都有效,尽管有点冗长!
我将其转换为 UIImage 上的类别:
UIImage+Crop.h
@interface UIImage (Crop)
- (UIImage*) imageByCroppingToRect:(CGRect)rect;
@end
UIImage+Crop.m
@implementation UIImage (Crop)
- (UIImage*) imageByCroppingToRect:(CGRect)rect
{
//create a context to do our clipping in
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//create a rect with the size we want to crop the image to
//the X and Y here are zero so we start at the beginning of our
//newly created context
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);
//create a rect equivalent to the full size of the image
//offset the rect by the X and Y we want to start the crop
//from in order to cut off anything before them
CGRect drawRect = CGRectMake(rect.origin.x * -1,
rect.origin.y * -1,
self.size.width,
self.size.height);
//draw the image to our clipped context using our offset rect
CGContextTranslateCTM(currentContext, 0.0, rect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextDrawImage(currentContext, drawRect, self.CGImage);
//pull the image from our cropped context
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
//pop the context to get back to the default
UIGraphicsEndImageContext();
//Note: this is autoreleased
return cropped;
}
@end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)