2015.12.7 Objective-c CoreGraphic

#import "myView.h"

@implementation myView

- (void)drawRect:(CGRect)rect {
    NSLog(@"drawRect被調用了");
//    [self drawLine];
    CGContextRef context = UIGraphicsGetCurrentContext();
//    [self drawRectWithContext: context];
//    [self drawArc:context];
    [self drawCurve:context];
}

-(void) drawLine
{
    //獲取圖形上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //設置線的起點位置
    CGContextMoveToPoint(context, 0, 0);
    //添加線段到點
    CGContextAddLineToPoint(context, 375/2.0, 667/2.0);
    CGContextAddLineToPoint(context, 375, 0);
    //繪製閉合路徑
    CGContextClosePath(context);
    
    CGContextMoveToPoint(context, 375/2.0, 667/2.0);
    CGContextAddLineToPoint(context, 375/2.0, 667);
    
    [[UIColor redColor]set];
    
    //設置線條寬度
    CGContextSetLineWidth(context, 5.0);
    //設置填充顏色
    CGContextSetRGBFillColor(context, 0, 0, 1, 1);
    
    //渲染顯示到view上
    CGContextDrawPath(context, kCGPathFillStroke);
    
}

-(void) drawRectWithContext : (CGContextRef)context
{
    //肯定矩形圖像的大小位置
    CGRect rect = CGRectMake(20, 20, 335, 50);
    CGContextAddRect(context, rect);
    //設置矩形的屬性
    [[UIColor blueColor]set];
    //繪製
    CGContextDrawPath(context, kCGPathFillStroke);
}

#pragma mark 繪製橢圓
-(void)drawEllipse : (CGContextRef)context
{
    CGRect rect = CGRectMake(50, 50, 275, 200);
    CGContextAddEllipseInRect(context, rect);
    //設置屬性
    [[UIColor purpleColor]set];
    //繪製
    CGContextDrawPath(context, kCGPathFillStroke);
}

#pragma mark 繪製弧
-(void) drawArc : (CGContextRef)context
{
    /*
     x: 中心點x座標
     y: 中心點y座標
     radius: 半徑
     startAngle: 起始弧度
     endAngle: 結束弧度
     clockwise: 是否逆時針繪製, 0則順時針繪製
     */
    CGContextAddArc(context, 375/2.0, 667/2.0, 100, 0.0, M_PI_2, 1);
    //設置屬性
    [[UIColor orangeColor]setFill];
    //繪製
    CGContextDrawPath(context, kCGPathStroke);
}

#pragma mark 繪製貝塞爾曲線
-(void) drawCurve : (CGContextRef) context
{
    CGContextMoveToPoint(context, 20, 500);
    /*
     cp1x: 第一個控制點x座標
     cp1y: 第一個控制點y座標
     cp2x: 第二個控制點x座標
     cp2y: 第二個控制點y座標
     x: 結束點x座標
     y: 結束點y座標
     */
    CGContextAddCurveToPoint(context, 20, 300, 295, 500, 355, 300);
    //設置屬性
    [[UIColor yellowColor]setFill];
    [[UIColor redColor]setStroke];
    
    //第一條切線
    CGContextMoveToPoint(context, 20, 500);
    CGContextAddLineToPoint(context, 20, 300);
    //第二條切線
    CGContextMoveToPoint(context, 355, 300);
    CGContextAddLineToPoint(context, 295, 500);
    
    //繪製
    CGContextDrawPath(context, kCGPathFillStroke);
    
    
}

//一個控制點的貝塞爾曲線
-(void) drawOneCurve : (CGContextRef) context
{
    //移動到曲線起始位置
    CGContextMoveToPoint(context, 20, 100);
    CGContextAddQuadCurveToPoint(context, 187.5, 0, 355, 100);
    [[UIColor yellowColor]setFill];
    [[UIColor redColor]setStroke];
    //繪製
    CGContextDrawPath(context, kCGPathFillStroke);
}





@end
相關文章
相關標籤/搜索