用CALayer.Mask(遮罩)实现iphone图标的水晶立体效果
昨天打群雄一下打了两个“破敌”,比较空虚,然后想起周末觉得自己应用中的图案都是纯用Path画的平面效果,比较土,就研究了一下如何实现点时尚的效果。
最终完成效果如下:
而原图效果只是这样:
通过遮罩完成以上效果,代码非常简单,不过需要准备遮罩层要用的alpha通道图片,对于非常非常不美工的我来说,用d版的fireworks搞掂:
但是你并不能直接把这个遮罩蒙在你的图片上,这样的话,图片会变暗,而且效果是跟你期望的相反的,正确的做法是在图片上蒙一个某种色的层,然后给这个层应用这个遮罩,这样最终效果就是我们期望的。
不过这里我们还需要一个简单的遮罩,应用在整个图上,把它修正成圆角(因为原图是四方的):
这个遮罩很简单,圆角alpha通道全透明,把原图的四角给全透掉(遮罩原理就是在原图像素的alpha改成遮罩的alpha)。
好了,整个代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(icon.bounds.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat components[4] = {0.0,0.4,0.0,1.0};
CGContextSetFillColor(ctx, components);
CGContextFillRect(ctx, CGRectMake(0, 0, icon.bounds.size.width, icon.bounds.size.height));
UIImage *background = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImage *mask = [UIImage imageNamed:@"IconBase.png"];
UIImage *roundCorner = [UIImage imageNamed:@"round-corner.png"];
icon.image = image;
CALayer* subLayer = [[CALayer layer] retain];
subLayer.frame = icon.bounds;
subLayer.contents = (id)[background CGImage];
CALayer* maskLayer = [[CALayer layer] retain];
maskLayer.frame = icon.bounds;
maskLayer.contents = (id)[mask CGImage];
[subLayer setMask:maskLayer];
[[icon layer] addSublayer:subLayer];
CALayer* roundCornerLayer = [[CALayer layer] retain];
roundCornerLayer.frame = icon.bounds;
roundCornerLayer.contents = (id)[roundCorner CGImage];
[[icon layer] setMask:roundCornerLayer];
[maskLayer release];
[subLayer release];
[roundCornerLayer release];
}
[super viewDidLoad];
UIGraphicsBeginImageContext(icon.bounds.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat components[4] = {0.0,0.4,0.0,1.0};
CGContextSetFillColor(ctx, components);
CGContextFillRect(ctx, CGRectMake(0, 0, icon.bounds.size.width, icon.bounds.size.height));
UIImage *background = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImage *mask = [UIImage imageNamed:@"IconBase.png"];
UIImage *roundCorner = [UIImage imageNamed:@"round-corner.png"];
icon.image = image;
CALayer* subLayer = [[CALayer layer] retain];
subLayer.frame = icon.bounds;
subLayer.contents = (id)[background CGImage];
CALayer* maskLayer = [[CALayer layer] retain];
maskLayer.frame = icon.bounds;
maskLayer.contents = (id)[mask CGImage];
[subLayer setMask:maskLayer];
[[icon layer] addSublayer:subLayer];
CALayer* roundCornerLayer = [[CALayer layer] retain];
roundCornerLayer.frame = icon.bounds;
roundCornerLayer.contents = (id)[roundCorner CGImage];
[[icon layer] setMask:roundCornerLayer];
[maskLayer release];
[subLayer release];
[roundCornerLayer release];
}