使用Core Graphics绘制阴影
图形上下文是支撑阴影的元素,这意味着你需要在上下文应用阴影,接着绘制需要阴影的形状,然后在上下文移除阴影
创建阴影的三个参数
1 需要应用阴影的图形上下文
2 偏移量
3 要应用到阴影的模糊值
注意点 :如果在同一视图上绘制两个图形,并且想添加阴影的话,只需添加一个就可以;
代码如下
1 先创建一个单视图工程
2 再创建一个UIView 的子类 视图
3 将自己创建的子类视图添加到根视图上
4 再自己创建的子视图上补充如下代码
#import "liView.h"
@implementation liView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
[self drawRectangles:nil];
//[self drawRectangle:nil];
//[self drawRectangleAtBottomOfScrren:nil];
}
- (void)drawRectangle:(id)sender
{
//创建第一条路径
CGMutablePathRef path = CGPathCreateMutable();
//定义矩形边界
CGRect rectangle = CGRectMake(10.0f, 10.0f, 100.0f, 300.0f);
//将矩形添加到自己创建的路径中
CGPathAddRect(path, NULL, rectangle);
//获得前后文
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//设置阴影 模糊值越高 越模糊
CGContextSetShadowWithColor(currentContext, CGSizeMake(10.0f, 10.0f), 20.0f, [[UIColor grayColor]CGColor]);
//把这条路径添加到获得的前后文中
CGContextAddPath(currentContext, path);
//为矩形填充颜色
[[UIColor yellowColor]setFill];
//为边框设计颜色
[[UIColor brownColor]setStroke];
//设置线条的宽度
CGContextSetLineWidth(currentContext, 5.0f);
//用你正在绘制的模型绘制你的路径
CGContextDrawPath(currentContext, kCGPathFillStroke);
//释放路径
CGPathRelease(path);
}
- (void)drawRectangles:(id)sender
{
//创建路径
CGMutablePathRef pathRef = CGPathCreateMutable();
//初始化需要绘制的两个模型
CGRect rectangle1 = CGRectMake(0, 0, 100, 200);
CGRect rectangle2 = CGRectMake(220, 0, 100, 200);
//将模型添加在数组中
CGRect rectangles[2] = {rectangle1,rectangle2};
//将数组添加到路径中
CGPathAddRects(pathRef,NULL , (const CGRect*)rectangles, 2);
//获取当前的前后文
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor(contextRef, CGSizeMake(10.0f, 10.0f), 20.0f, [[UIColor grayColor]CGColor]);
//将路径添加在前后文中
CGContextAddPath(contextRef, pathRef);
//为矩形填充颜色
[[UIColor yellowColor]setFill];
//为边框设置颜色
[[UIColor greenColor]setStroke];
//设置边框的宽度
CGContextSetLineWidth(contextRef, 5);
//用将要绘制的模型来绘制路径
CGContextDrawPath(contextRef, kCGPathFillStroke);
//释放路径
CGPathRelease(pathRef);
}
- (void)drawRectangleAtBottomOfScrren:(id)sender
{
CGMutablePathRef path = CGPathCreateMutable();
CGRect rectangle = CGRectMake(210, 10, 100, 300);
CGPathAddRect(path, NULL, rectangle);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context, path);
[[UIColor blueColor]setStroke];
[[UIColor redColor]setFill];
CGContextDrawPath(context, kCGPathEOFillStroke);
CGPathRelease(path);
}
@end