画圆、矩形、椭圆

2016-08-24  本文已影响54人  Z了个L

// DrawView.h
#import <UIKit/UIKit.h>

@interface DrawView : UIView

@end

// DrawView.m

#import "DrawView.h"

@implementation DrawView


- (void)awakeFromNib {
    
    //描述一个椭圆
    //UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 200, 100)];
    //绘制路径
    //[path stroke];

}



- (void)drawRect:(CGRect)rect {
    
    //描述一个椭圆
    //UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 200, 200)];
    //绘制路径
    //[[UIColor yellowColor] set];
    //[path fill];
    
    //画弧
    //Center:弧所在的圆心
    //radius:圆的半径
    //startAngle:开始角度,圆的最右侧为0度
    //endAngle:截至角度,向下为正,向上为负.
    //clockwise:时针的方向,yes:顺时针 no:逆时针

//    NSLog(@"self.center=%@",NSStringFromCGPoint(self.center));
    
//    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
//    CGFloat radius = rect.size.width * 0.5 - 10;
//    CGFloat startA = 0;
//    CGFloat endA = -M_PI_2;
//    //画弧的路径
//    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:NO];
//    
//    //画扇形
//    //添加一根线到圆心
//    [path addLineToPoint:center];
//    //关闭路径(自动的从路径的终点连接到路径的起点)
//    //[path closePath];
//    [[UIColor redColor] set];
//    //使用fill在填充之前,自动的关闭路径
//    [path fill];
    
    [self drawRect];
    //1.获取上下文->2.描述路径->3.把路径添加到上下文->4.把上下文的内容渲染到View的layer.
    
}

//画矩形
- (void)drawRect {
    //1.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //2.描述路径
    //矩形
//    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 200, 200)];
    //画圆角矩形
    //cornerRadius:圆角半径
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(50, 50, 200, 200) cornerRadius:100];
    
    //3.把路径添加到上下文
    CGContextAddPath(ctx, path.CGPath);
    CGContextSetLineWidth(ctx, 5);
    
    [[UIColor redColor] set];
    
    //4.把上下文的内容渲染到View的layer.
    CGContextStrokePath(ctx);
//    CGContextFillPath(ctx);
}


- (void)drawRect:(CGRect)rect {
//    [self drawRectOne];
    [self drawRectTwo];
}

// 一个椭圆两种方式
- (void)drawRectOne {
    //1.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //2.描述路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 200, 100)];
    //3.把路径添加到上下文
    CGContextAddPath(ctx, path.CGPath);
    //4.把上下文的内容渲染到View的layer.
    CGContextStrokePath(ctx);
}

// 一个椭圆两种方式
- (void)drawRectTwo {
    // 描述一个椭圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 200, 100)];
    //绘制路径
    [path stroke];
    // [path stroke];做了下面4步操作
    // 1.获取上下文->2.描述路径->3.把路径添加到上下文->4.把上下文的内容渲染到View的layer.
}


//drawAtPoint不会自动换行
//[str drawAtPoint:CGPointMake(0, 0) withAttributes:dict];
//drawInRect会自动换行
[str drawInRect:self.bounds withAttributes:dict];

// 当系统自动调用drawRect方法时会自动创建跟View相关联的上下文
// 重绘setNeedsDisplay系统会自动调用drawRect:
[self setNeedsDisplay];
@end


上一篇 下一篇

猜你喜欢

热点阅读