2个重要的方法
//只能系统调用 (手动调用self setNeedsDisplay)进行重绘制,然后会调用此方法。
- (void)drawRect:(CGRect)rect {
drawClip();
}
//画线
void drawLine(){
CGContextRef ctx = UIGraphicsGetCurrentContext();
/保存上下文状态
CGContextSaveGState(ctx);
//上下文旋转
CGContextRotateCTM(ctx, M_PI/8);
//缩放
CGContextScaleCTM(ctx, 0.8, 0.8);
//平移动
CGContextTranslateCTM(ctx, 50, 50);
CGContextMoveToPoint(ctx, 20, 20);
CGContextAddLineToPoint(ctx, 150, 100);
CGContextAddLineToPoint(ctx, 50, 80);
CGContextClosePath(ctx);
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
CGContextSetLineWidth(ctx, 5);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineJoin(ctx, kCGLineJoinRound);
/ /恢复到保存上下文时候的状态
CGContextRestoreGState(ctx);
CGContextStrokePath(ctx);
}
//画矩形
void drawMyRect(){
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddRect(ctx, CGRectMake(50, 50, 100, 100));
CGContextStrokePath(ctx);
}
//画椭圆
void drawCircle(){
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 150));
CGContextStrokePath(ctx);
}
//画圆弧
void drawArc(){
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddArc(ctx, 100, 100, 80, M_PI_2, M_PI, 0);
CGContextStrokePath(ctx);
}
//画文字
void drawText(){
NSString *str = @"卧槽,最近太倒霉了啊 啊啊啊 ";
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor redColor];
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:50];
[str drawAtPoint:CGPointMake(100, 100) withAttributes:attrs];
}
//画图片
void drawImage(){
UIImage *image = [UIImage imageNamed:@"1"];
//[image drawAtPoint:CGPointMake(50, 50)];
[image drawAsPatternInRect:CGRectMake(100, 100, 25, 25)];
}
//图片裁剪
void drawClip(){
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 50, 50));
CGContextClip(ctx);
CGContextFillPath(ctx);
UIImage *image = [UIImage imageNamed:@"1"];
//[image drawAtPoint:CGPointMake(50, 50)];
[image drawAsPatternInRect:CGRectMake(100, 100, 50, 50)];
}