我需要在用户的照片周围绘制阴影。我通过绘制一个圆圈然后裁剪上下文来绘制这些圆圈照片。这里是我的代码片段:剪辑后无法绘制阴影
+ (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;
}
这种方法的问题显然是它击中我的应用程序的性能 - 拉两次圈加它的实现代码如下。 我的问题是我怎样才能避免绘制第二个圆,并在裁剪上下文后绘制阴影?我确实保存并恢复了状态,但没有帮助,我可能做错了。我还假定drawInRect关闭当前路径,这就是为什么阴影不知道在哪里绘制自己。我应该再次调用CGContextAddEllipseInRect然后绘制阴影吗?
谢谢先生,我一直在等你过去几天的答案。甚至在Twitter上发布了这个问题;)我一直在关注你的博客和你在过去一个月的SO上的答案:)。我是Core Graphics的新手,你的专业知识对我很有帮助。再次感谢您提供丰富的答案。现在我知道我出错了。 – macL0vin
我很高兴它有帮助。关键是,这种表现可能不直观,而且依情况而定。 –