Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Triangle iOS

The code below is drawing me a circle, how can I modify the existing code to draw a triangle instead?

    _colorDotLayer = [CALayer layer];

    CGFloat width = self.bounds.size.width-6;
    _colorDotLayer.bounds = CGRectMake(0, 0, width, width);
    _colorDotLayer.allowsGroupOpacity = YES;
    _colorDotLayer.backgroundColor = self.annotationColor.CGColor;
    _colorDotLayer.cornerRadius = width/2;
    _colorDotLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
like image 404
Clip Avatar asked Aug 30 '14 01:08

Clip


People also ask

What is Cashapelayer Swift?

A layer that draws a cubic Bezier spline in its coordinate space.


2 Answers

While there are shown several Core Graphics solution, I want to add a Core Animation based solution.

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBezierPath* trianglePath = [UIBezierPath bezierPath];
    [trianglePath moveToPoint:CGPointMake(0, view3.frame.size.height-100)];
    [trianglePath addLineToPoint:CGPointMake(view3.frame.size.width/2,100)];
    [trianglePath addLineToPoint:CGPointMake(view3.frame.size.width, view2.frame.size.height)];
    [trianglePath closePath];

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

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, size.width, size.height)];

    view.backgroundColor = [UIColor colorWithWhite:.75 alpha:1];
    view.layer.mask = triangleMaskLayer;
    [self.view addSubview:view];
}

code based on my blog post.

like image 74
vikingosegundo Avatar answered Oct 04 '22 20:10

vikingosegundo


@implementation TriangleView {
    CAShapeLayer *_colorDotLayer;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    if (_colorDotLayer == nil) {
        _colorDotLayer = [CAShapeLayer layer];
        _colorDotLayer.fillColor = self.annotationColor.CGColor;
        [self.layer addSublayer:_colorDotLayer];
    }

    CGRect bounds = self.bounds;
    CGFloat radius = (bounds.size.width - 6) / 2;
    CGFloat a = radius * sqrt((CGFloat)3.0) / 2;
    CGFloat b = radius / 2;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, -radius)];
    [path addLineToPoint:CGPointMake(a, b)];
    [path addLineToPoint:CGPointMake(-a, b)];
    [path closePath];
    [path applyTransform:CGAffineTransformMakeTranslation(CGRectGetMidX(bounds), CGRectGetMidY(bounds))];
    _colorDotLayer.path = path.CGPath;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.annotationColor = [UIColor redColor];
}

@end

Result:

triangle view

like image 38
rob mayoff Avatar answered Oct 04 '22 20:10

rob mayoff