- (UIImage *)roundedCornerImage:(NSInteger)cornerSize borderSize:(NSInteger)borderSize {
// If the image does not have an alpha layer, add one
UIImage *image = [self imageWithAlpha];
// Build a context that's the same dimensions as the new size
CGBitmapInfo info = CGImageGetBitmapInfo(image.CGImage);
CGContextRef context = CGBitmapContextCreate(NULL,
image.size.width,
image.size.height,
CGImageGetBitsPerComponent(image.CGImage),
0,
CGImageGetColorSpace(image.CGImage),
CGImageGetBitmapInfo(image.CGImage));
// Create a clipping path with rounded corners
CGContextBeginPath(context);
[self addRoundedRectToPath:CGRectMake(borderSize, borderSize, image.size.width - borderSize * 2, image.size.height - borderSize * 2)
context:context
ovalWidth:cornerSize
ovalHeight:cornerSize];
CGContextClosePath(context);
CGContextClip(context);
// Draw the image to the context; the clipping path will make anything outside the rounded rect transparent
CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
// Create a CGImage from the context
CGImageRef clippedImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
// Create a UIImage from the CGImage
UIImage *roundedImage = [UIImage imageWithCGImage:clippedImage];
CGImageRelease(clippedImage);
return roundedImage;
}
我有上面的方法,并正在添加圆角推特个人资料图像。对于大多数图像来说,这是非常棒的。有几个错误会导致以下错误:
:CGBitmapContextCreate:不支持的参数组合:8整数位/组件;32位/像素;3分量颜色空间;kCGImageAlphaLast;96字节/行。
我已经做了一些调试,在创建上下文时,与导致错误的图像和那些不是错误的图像的唯一区别是参数CGImageGetBitmapInfo(image.CGImage)。这会引发错误并导致上下文为null。我尝试将最后一个参数设置为kCGImageAlphaPremultipliedLast,但也没有效果。这一次画的图像质量要低得多。有没有一种方法可以得到一个更高质量的形象,与他们其他人一样?到图片的路径是通过推特,所以不确定他们是否有不同的,你可以拉。
我也看到了关于这个错误的其他问题。没有人解决过这个问题。我看到了this post,但是错误的图像在那之后是完全模糊的。将宽度和高度转换为NSInteger也不起作用。下面是两张个人资料图片的截图,以及它们的质量。第一种是导致错误。
有人知道这是什么问题吗?
谢谢一吨。这让我很难受。
发布于 2012-02-29 23:41:19
iOS不支持kCGImageAlphaLast
。您需要使用kCGImageAlphaPremultipliedLast
。
您还需要处理您的初始图像的比例。您的当前代码没有,所以如果图像的缩放范围为2.0,它会降低图像的采样量。
您可以通过使用UIKit函数和类编写整个函数。UIKit将为您处理缩放;当您要求原始图像创建图形上下文时,您只需传递原始图像的比例即可。
- (UIImage *)roundedCornerImage:(NSInteger)cornerSize borderSize:(NSInteger)borderSize {
// If the image does not have an alpha layer, add one
UIImage *image = [self imageWithAlpha];
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); {
CGRect imageRect = (CGRect){ CGPointZero, image.size };
CGRect borderRect = CGRectInset(imageRect, borderSize, borderSize);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:borderRect
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(cornerSize, cornerSize)];
[path addClip];
[image drawAtPoint:CGPointZero];
}
UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return roundedImage;
}
如果您的imageWithAlpha
方法本身从另一个UIImage
创建了一个UIImage
,那么它也需要传播这个规模。
https://stackoverflow.com/questions/9508163
复制相似问题