- 貝瑟爾路徑與C語言路徑結(jié)合.
- (void)drawRect:(CGRect)rect {
//獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//創(chuàng)建橢圓路徑
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 50, 200, 100)];
/**
* 矩陣操作必須在添加路徑之前
*/
//縮放
CGContextScaleCTM(ctx, 0.5, 0.5);
//移動
CGContextTranslateCTM(ctx, 20, 200);
//旋轉(zhuǎn)
CGContextRotateCTM(ctx, M_PI_2);
//將路徑添加至上下文
CGContextAddPath(ctx, path.CGPath);
//設(shè)置顏色
[[UIColor redColor] set];
//渲染上下文
CGContextFillPath(ctx);
}
效果圖:

原圖

縮放

位移

旋轉(zhuǎn)
注意:這幾種效果可疊加.
- 繪制文字:
- (void)drawRect:(CGRect)rect {
//創(chuàng)建富文本字典
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//設(shè)置富文本字體
dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
//設(shè)置富文本背景顏色
// dict[NSBackgroundColorAttributeName] = [UIColor redColor];
//設(shè)置繪制線寬
dict[NSStrokeWidthAttributeName] = @10;
//創(chuàng)建shadow對象
NSShadow *shadow = [[NSShadow alloc] init];
//設(shè)置shadow模糊度
shadow.shadowBlurRadius = 2;
//設(shè)置shadow的顏色
shadow.shadowColor = [UIColor orangeColor];
//設(shè)置shadow的偏移量
shadow.shadowOffset = CGSizeMake(5, 5);
//設(shè)置富文本陰影效果
dict[NSShadowAttributeName] = shadow;
//創(chuàng)建文字
NSString *str = @"iOS基礎(chǔ)知識";
//繪制文字
[str drawAtPoint:CGPointMake(50, 50) withAttributes:dict];
}
效果圖:

繪制文字
- 繪制圖片:
- (void)drawRect:(CGRect)rect {
//創(chuàng)建圖片,同時設(shè)置圖片內(nèi)容,此方法創(chuàng)建的image的尺寸與圖片尺寸相同
UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Snip20160427_8"]];
//通過此方法繪制圖片時,坐標(biāo)默認(rèn)在父控件的原點位置
[imageV drawRect:CGRectMake(100, 50, imageV.frame.size.width, imageV.frame.size.height)];
}
- (void)drawRect:(CGRect)rect {
// image.size = CGSizeMake(50, 50);
//繪制圖片,可控制坐標(biāo)位置
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 {
//創(chuàng)建image
UIImage *image = [UIImage imageNamed:@"Snip20160427_10"];
//繪制圖片
[image drawAtPoint:CGPointMake(0, snow)];
//設(shè)置image的位置下移
snow += 10;
//重復(fù)
if (snow > self.frame.size.height) {
snow = 0;
}
}
- (void)awakeFromNib{
//創(chuàng)建定時器
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeChange)];
//添加主運(yùn)行循環(huán)
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
//定時器調(diào)用的方法
- (void)timeChange{
//重繪
[self setNeedsDisplay];
}
效果圖:

雪花效果