[IOS] How to draw triangles through UIView

1. Create an implementation CustomView that inherits UIView

 

2. Override drawRect

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Draw a triangle
    CGContextBeginPath(context);
    CGContextMoveToPoint   (context, self.bounds.size.width/2, 0);  // top
    CGContextAddLineToPoint(context, 0, self.bounds.size.height);  // right
    CGContextAddLineToPoint(context, self.bounds.size.width,self.bounds.size.height);  // left
    CGContextClosePath(context);
    
    CGContextSetRGBFillColor(context, 1, 1, 1, 1);
    CGContextFillPath(context);
    
}

 

3. Use

CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(mainScreen.size.width/2-50, mainScreen.size.height/2-50, 100, 100)];
    customView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:customView];

 

 refer to:

1. IOS uses CGContextRef to draw various graphics (text, circle, line, arc, rectangle, sector, ellipse, triangle, rounded rectangle, Bezier curve, picture) : http://blog.csdn.net/rhljiayou /article/details/9919713

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326213885&siteId=291194637