我正在尝试将图像添加到已分组的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, fw, fh, fw/2, fh, 0);
NSLog(@"bottom? %d", bottom);
if (top) {
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 3);
} else {
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 0);
}
if (bottom) {
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 3);
} else {
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 0);
}
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 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, 0, w, h);
addRoundedRectToPath(context, rect, 4, 4, top, bottom);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), source.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
实现这些功能,然后在
indexPath
委托(delegate)方法中检查cellForRowAtIndexPath
以确定要倒圆的角。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;
}
关于objective-c - 如何将UIImage添加到分组的UITableViewCell中,以使它变得圆满?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2118613/