- 贝瑟尔路径与C语言路径结合.
- (void)drawRect:(CGRect)rect {
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//创建椭圆路径
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 50, 200, 100)];
/**
* 矩阵操作必须在添加路径之前
*/
//缩放
CGContextScaleCTM(ctx, 0.5, 0.5);
//移动
CGContextTranslateCTM(ctx, 20, 200);
//旋转
CGContextRotateCTM(ctx, M_PI_2);
//将路径添加至上下文
CGContextAddPath(ctx, path.CGPath);
//设置颜色
[[UIColor redColor] set];
//渲染上下文
CGContextFillPath(ctx);
}
效果图:
原图 缩放 位移 旋转注意:这几种效果可叠加.
- 绘制文字:
- (void)drawRect:(CGRect)rect {
//创建富文本字典
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//设置富文本字体
dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
//设置富文本背景颜色
// dict[NSBackgroundColorAttributeName] = [UIColor redColor];
//设置绘制线宽
dict[NSStrokeWidthAttributeName] = @10;
//创建shadow对象
NSShadow *shadow = [[NSShadow alloc] init];
//设置shadow模糊度
shadow.shadowBlurRadius = 2;
//设置shadow的颜色
shadow.shadowColor = [UIColor orangeColor];
//设置shadow的偏移量
shadow.shadowOffset = CGSizeMake(5, 5);
//设置富文本阴影效果
dict[NSShadowAttributeName] = shadow;
//创建文字
NSString *str = @"iOS基础知识";
//绘制文字
[str drawAtPoint:CGPointMake(50, 50) withAttributes:dict];
}
效果图:
绘制文字- 绘制图片:
- (void)drawRect:(CGRect)rect {
//创建图片,同时设置图片内容,此方法创建的image的尺寸与图片尺寸相同
UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Snip20160427_8"]];
//通过此方法绘制图片时,坐标默认在父控件的原点位置
[imageV drawRect:CGRectMake(100, 50, imageV.frame.size.width, imageV.frame.size.height)];
}
- (void)drawRect:(CGRect)rect {
// image.size = CGSizeMake(50, 50);
//绘制图片,可控制坐标位置
UIImage *image = [UIImage imageNamed:@"Snip20160427_10"];
[image drawAtPoint:CGPointMake(50, 50)];
}
效果图:
drawRect drawAtPoint- 雪花效果:
//定义变量
static CGFloat snow = 0;
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
//创建image
UIImage *image = [UIImage imageNamed:@"Snip20160427_10"];
//绘制图片
[image drawAtPoint:CGPointMake(0, snow)];
//设置image的位置下移
snow += 10;
//重复
if (snow > self.frame.size.height) {
snow = 0;
}
}
- (void)awakeFromNib{
//创建定时器
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeChange)];
//添加主运行循环
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
//定时器调用的方法
- (void)timeChange{
//重绘
[self setNeedsDisplay];
}
效果图:
雪花效果
网友评论