创建顶部有三角形的 UIView

Create UIView with triangle on top

我目前在我的应用程序中使用以下图片,但是,今后我想使用 UIView 以编程方式创建它,以便我可以更好地控制它。

我尝试了以下但无法达到预期的结果:

像我正在做的那样使用 .png 或以编程方式创建所述视图是否更优化(性能方面而不是时间方面)?

我在 UITableViewCell 秒内用聊天式气泡做了类似的事情。

这是我用来实现效果的代码。您可以轻松调整 UIBezierPath 以满足您的需求:

- (void)drawBubbleForRect:(CGRect)rect {

    CGRect bubbleRect       = // Get your rect somehow, or just use rect

    // The size of the "blip" in the side of the chat bubble (which points up for this bubble)
    CGFloat blipWidth       = 11.0f;
    CGFloat blipHeight      = 7.0f;
    CGFloat blipLeft        = CGRectGetMinX(bubbleRect) + blipWidth;
    CGFloat blipMiddle      = blipLeft + (blipWidth / 2.0f);
    CGFloat blipRight       = blipLeft + blipWidth;
    CGFloat blipBottom      = CGRectGetMinY(bubbleRect);
    CGFloat blipTop         = blipBottom - blipHeight;
    CGFloat cornerRadius    = 3.0f;

    UIBezierPath *path      = [UIBezierPath bezierPath];
    [path moveToPoint:      CGPointMake(CGRectGetMinX(bubbleRect) + cornerRadius,   blipBottom)];
    [path addLineToPoint:   CGPointMake(blipLeft,                                   blipBottom)];
    [path addLineToPoint:   CGPointMake(blipMiddle,                                 blipTop)];
    [path addLineToPoint:   CGPointMake(blipRight,                                  blipBottom)];
    [path addLineToPoint:   CGPointMake(CGRectGetMaxX(bubbleRect) - cornerRadius,   blipBottom)];
    [path addArcWithCenter: CGPointMake(CGRectGetMaxX(bubbleRect) - cornerRadius,   blipBottom + cornerRadius)                  radius:cornerRadius startAngle:(3 * M_PI / 2)   endAngle:0              clockwise:YES];
    [path addLineToPoint:   CGPointMake(CGRectGetMaxX(bubbleRect),                  CGRectGetMaxY(bubbleRect) - cornerRadius)];
    [path addArcWithCenter: CGPointMake(CGRectGetMaxX(bubbleRect) - cornerRadius,   CGRectGetMaxY(bubbleRect) - cornerRadius)   radius:cornerRadius startAngle:0                endAngle:(M_PI / 2)     clockwise:YES];
    [path addLineToPoint:   CGPointMake(CGRectGetMinX(bubbleRect) + cornerRadius,   CGRectGetMaxY(bubbleRect))];
    [path addArcWithCenter: CGPointMake(CGRectGetMinX(bubbleRect) + cornerRadius,   CGRectGetMaxY(bubbleRect) - cornerRadius)   radius:cornerRadius startAngle:(M_PI / 2)       endAngle:M_PI           clockwise:YES];
    [path addLineToPoint:   CGPointMake(CGRectGetMinX(bubbleRect),                  CGRectGetMinY(bubbleRect) + cornerRadius)];
    [path addArcWithCenter: CGPointMake(CGRectGetMinX(bubbleRect) + cornerRadius,   CGRectGetMinY(bubbleRect) + cornerRadius)   radius:cornerRadius startAngle:M_PI             endAngle:(3 * M_PI / 2) clockwise:YES];

    [someColor setFill];
    [path fill];

}