【发布时间】:2016-04-21 08:42:39
【问题描述】:
我需要在用户照片周围绘制阴影。我通过画一个圆圈然后剪裁上下文来绘制那些圆形照片。这是我的代码的 sn-p:
+ (UIImage*)roundImage:(UIImage*)img imageView:(UIImageView*)imageView withShadow:(BOOL)shadow
{
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(context, CGRectMake(0,0, imageView.width, imageView.height));
CGContextSaveGState(context);
CGContextClip(context);
[img drawInRect:imageView.bounds];
CGContextRestoreGState(context);
if (shadow) {
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 5, [kAppColor lighterColor].CGColor);
}
CGContextDrawPath(context, kCGPathFill);
UIImage* roundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return roundImage;
}
但是在裁剪区域后,我无法在下面绘制阴影。所以我不得不在照片后面再画一个有阴影的圆圈。
+ (UIImage *)circleShadowFromRect:(CGRect)rect circleDiameter:(CGFloat)circleDiameter shadowColor:(UIColor*)color
{
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGFloat circleStartPointX = CGRectGetMidX(rect) - circleDiameter * 0.5;
CGFloat circleStartPointY = CGRectGetMidY(rect) - circleDiameter * 0.5;
CGContextAddEllipseInRect(context, CGRectMake(circleStartPointX,circleStartPointY, circleDiameter, circleDiameter));
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 5, color.CGColor);
CGContextDrawPath(context, kCGPathFill);
UIImage *circle = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return circle;
}
这种方法的问题显然是它影响了我的应用程序的性能 - 画了两倍以上的圆圈加上它是 tableview。 我的问题是如何避免在剪切上下文后绘制第二个圆圈并绘制阴影?我确实保存并恢复了状态,但它没有帮助,我可能做错了。我还假设 drawInRect 关闭了当前路径,这就是为什么阴影不知道在哪里绘制自己。我应该再次调用 CGContextAddEllipseInRect 然后绘制阴影吗?
【问题讨论】:
标签: ios objective-c core-graphics quartz-graphics