Search code examples
iosobjective-ccore-graphics

How to draw trapezoid shape in iOS?


I need help to draw trapezoid shapes in iOS.

I am using the following code to draw the Pink shape, but it is not working:

UIBezierPath* trianglePath = [UIBezierPath bezierPath];
[trianglePath moveToPoint:CGPointMake(0, 0)];
[trianglePath addLineToPoint:CGPointMake(topView.frame.size.width, topView.frame.size.height/2)];
[trianglePath addLineToPoint:CGPointMake(100, topView.frame.size.height/2)];

CAShapeLayer *triangleMaskLayer = [CAShapeLayer layer];
[triangleMaskLayer setPath:trianglePath.CGPath];

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,topView.frame.size.height-150, 200, 150)];
view.layer.mask = triangleMaskLayer;
[self.view addSubview:view];

How can I draw the pink-colored shape?enter image description here


Solution

  • -(void)TriangularPinkView{
        UIBezierPath *path = [UIBezierPath bezierPath];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.strokeColor = [[UIColor redColor] CGColor];
        shapeLayer.lineWidth = 0.5;
    
        CGPoint start = CGPointMake(CGRectGetMinX(self.pinkView.frame), CGRectGetMidY(self.pinkView.frame)+CGRectGetHeight(self.pinkView.frame)*.25);
        [path moveToPoint:start];
        [path addLineToPoint:CGPointMake(CGRectGetMaxX(self.pinkView.frame), CGRectGetMidY(self.pinkView.frame))];
        [path addLineToPoint:CGPointMake(CGRectGetMaxX(self.pinkView.frame), CGRectGetMaxY(self.pinkView.frame))];
        [path addLineToPoint:CGPointMake(CGRectGetMinX(self.pinkView.frame), CGRectGetMaxY(self.pinkView.frame))];
    
    
        shapeLayer.path = [path CGPath];
    //    shapeLayer.fillRule = kCAFillRuleEvenOdd;
        shapeLayer.fillColor = [[UIColor redColor] CGColor];
    
        [self.view.layer addSublayer:shapeLayer];
    }