先使用Core Graphics自己画出了一个圆角矩形图片,再设置边框宽度和颜色,也不会触发离屏渲染
iconImage = [UIImage createRoundedRectImage:self.iconImage size:CGSizeMake(100, 50) radius:25];
iconView = [[UIImageView alloc] initWithImage:iconImage];
iconView.layer.borderWidth = 2.0;
iconView.layer.borderColor = UIColor.redColor.CGColor;
iconView.frame = CGRectMake(20, 5, 100, 50);
iconView.layer.cornerRadius = 25;
iconView.layer.masksToBounds = YES;
[self.view addSubview:iconView];
#import <UIKit/UIKit.h>
@interface UIImage (DSRoundImage)
+ (id)createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(int)radius;
@end
#import "UIImage+DSRoundImage.h"
@implementation UIImage (DSRoundImage)
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
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); // Start at lower right corner
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
+ (id)createRoundedRectImage:(UIImage *)image size:(CGSize)size radius:(int)radius{
size = CGSizeMake(size.width*2, size.height*2);
radius = radius*2;
UIImage * img = image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 4 * size.width, colorSpace, kCGImageAlphaPremultipliedFirst);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
CGContextBeginPath(context);
addRoundedRectToPath(context, rect, radius, radius);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
img = [UIImage imageWithCGImage:imageMasked];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageMasked);
return img;
}
@end
网友评论