如何使用Core Graphics绘制三角形 - Mac?

时间:2011-07-10 03:59:02

标签: objective-c cocoa macos

我想要这样的事情:(轻的部分,忽略背景)

example triangle

我如何使用Cocoa绘制它?在drawRect:?我不知道怎么画。

3 个答案:

答案 0 :(得分:20)

使用NSBezierPath

- (void)drawRect:(NSRect)rect
{
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path moveToPoint:NSMakePoint(0, 0)];
    [path lineToPoint:NSMakePoint(50, 100)];
    [path lineToPoint:NSMakePoint(100, 0)];
    [path closePath];
    [[NSColor redColor] set];
    [path fill];
}

这应该让你开始,它在100x100大小的视图上绘制一个红色三角形。您通常会根据视图的大小动态计算坐标,而不是使用硬编码值。

答案 1 :(得分:4)

iOS + Swift

(1)创建一个Swift扩展

// Centered, equilateral triangle
extension UIBezierPath {
    convenience init(equilateralSide: CGFloat, center: CGPoint) {
        self.init()
        let altitude = CGFloat(sqrt(3.0) / 2.0 * equilateralSide)
        let heightToCenter = altitude / 3
        moveToPoint(CGPoint(x:center.x, y:center.y - heightToCenter*2))
        addLineToPoint(CGPoint(x:center.x + equilateralSide/2, y:center.y + heightToCenter))
        addLineToPoint(CGPoint(x:center.x - equilateralSide/2, y:center.y + heightToCenter))
        closePath()
    }
}

(2)覆盖drawRect

override func drawRect(rect: CGRect) {
    let path = UIBezierPath(
        equilateralSide: self.bounds.size.width,
        center: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2))

    self.tintColor.set()
    path!.fill()
}

答案 2 :(得分:1)

iOS + Swift5(更新的上下文处理,允许使用diff宽度)

        let triangleWidth: CGFloat = 8.0
        let heightToCenter: CGFloat = 4.0 // This controls how "narrow" the triangle is
        let center: CGPoint = centerPoint
        context.setFillColor(UIColor.red.cgColor)
        context.move(to: CGPoint(x:center.x, y:center.y - heightToCenter*2))
        context.addLine(to: CGPoint(x:center.x + triangleWidth/2, y:center.y + heightToCenter))
        context.addLine(to: CGPoint(x:center.x - triangleWidth/2, y:center.y + heightToCenter))
        context.closePath()
        context.fillPath()