我正在尝试将图像添加到分组的UITableView中的表格单元格中,但图像的边角不会被剪切.什么是最好的方式去剪裁这些(除了剪贴他们在Photoshop?表内容是动态的.)
例如,表中的第一个图像只需要左上角的四舍五入.
解决方法
这是我的解决方案,可以使用一些重构:
void addRoundedRectToPath(CGContextRef context,CGRect rect,float ovalWidth,float ovalHeight,BOOL top,BOOL bottom)
{
float fw,fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context,rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context,CGRectGetMinX(rect),CGRectGetMinY(rect));
CGContextScaleCTM (context,ovalWidth,ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMovetoPoint(context,fw,fh/2);
CGContextAddArcToPoint(context,fh,fw/2,0);
NSLog(@"bottom? %d",bottom);
if (top) {
CGContextAddArcToPoint(context,fh/2,3);
} else {
CGContextAddArcToPoint(context,0);
}
if (bottom) {
CGContextAddArcToPoint(context,0);
}
CGContextAddArcToPoint(context,0);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
- (UIImage *)roundCornersOfImage:(UIImage *)source roundTop:(BOOL)top roundBottom:(BOOL)bottom {
int w = source.size.width;
int h = source.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,w,h,8,4 * w,colorSpace,kCGImageAlphaPremultipliedFirst);
CGContextBeginPath(context);
CGRect rect = CGRectMake(0,h);
addRoundedRectToPath(context,rect,4,top,bottom);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context,CGRectMake(0,h),source.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
实现这些功能,然后检查cellForRowAtIndexPath委托方法中的indexPath,以确定要舍入的角.
if (indexPath.row == 0) {
cell.imageView.image = [self roundCornersOfImage:coverImage roundTop:YES roundBottom:NO];
} else if (indexPath.row == [indexPath length]) {
cell.imageView.image = [self roundCornersOfImage:coverImage roundTop:NO roundBottom:YES];
} else {
cell.imageView.image = coverImage;
}