UIView with custom shape

2019-08-10 12:31发布

I want to have a UIElement (any of UIView, UIButton, UILabel etc.) with custom shape lets say a triangle. How do you suggest to achieve it.
Thanks in advance.

1条回答
Fickle 薄情
2楼-- · 2019-08-10 12:38

Here is a sample of a UIView subclass (triangle):

@implementation TriangleView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextBeginPath(ctx);

    CGContextMoveToPoint   (ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));  // top left
    CGContextAddLineToPoint(ctx, CGRectGetMidX(rect), CGRectGetMinY(rect));  // mid right
    CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));  // bottom left

    CGContextClosePath(ctx);

    CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
    CGContextFillPath(ctx);

}

@end
查看更多
登录 后发表回答