UIImage暗影麻烦 [英] UIImage Shadow Trouble
问题描述
我正在尝试为图像添加一个小阴影,就像App Store中的图标阴影一样。现在我正在使用以下代码来围绕我的图像的角落。有谁知道我怎么能适应它来添加一个小阴影?
I'm trying to add a small shadow to an image, much like the icon shadows in the App Store. Right now I'm using the following code to round the corners of my images. Does anyone know how I can adapt it to add a small shadow?
- (UIImage *)roundCornersOfImage:(UIImage *)source height:(int)height width:(int)width {
int w = width;
int h = height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef imageContext = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextBeginPath(imageContext);
CGRect rect = CGRectMake(0, 0, w, h);
addRoundedRectToPath(imageContext, rect, 10, 10);
CGContextClosePath(imageContext);
CGContextClip(imageContext);
CGContextDrawImage(imageContext, CGRectMake(0, 0, w, h), source.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(imageContext);
CGContextRelease(imageContext);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
addRoundedRectToPath是指另一种明显围绕角落的方法。
"addRoundedRectToPath" refers to another method that obviously rounds the corners.
推荐答案
首先,这里是文档的链接:
First, here's a link to the documentation:
接下来,在调用CGContextDrawImage(...)之前尝试添加类似的东西:
Next, try adding something like this right before the call to CGContextDrawImage(...):
CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
CGColorRef shadowColor = CGColorCreate(colorSpace, components);
CGContextSetShadowWithColor(imageContext, CGSizeMake(3, 3), 2, shadowColor);
CGColorRelease(shadowColor);
之后,调用CGContextSetShadowWithColor(.....),一切都应该用阴影画出来被(3,3)点偏移,并以2.0点模糊半径绘制。您可能想要调整黑色的不透明度(组件中的第四个组件),并更改阴影参数。
After, the call to CGContextSetShadowWithColor(.....), everything should draw with a shadow that is offset by (3, 3) points, and drawn with a 2.0 point blur radius. You'll probably want to tweak the opacity of the black color (the forth component in components), and change the shadow parameters.
如果您想停止绘图在某些时候有阴影,你需要在调用CGContextSetShadowWithColor之前保存图形上下文,并在你想要用阴影停止绘图时恢复它。
If you'd like to stop drawing with a shadow at some point, you need to save the graphics context before calling CGContextSetShadowWithColor, and restore it when you want to stop drawing with a shadow.
这篇关于UIImage暗影麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!