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

Nam*_*mes 4 macos cocoa objective-c

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

示例三角形

我怎么能用Cocoa绘制这个?在drawRect:?我不知道怎么画.

omz*_*omz 22

用途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];
}
Run Code Online (Sandbox Code Playgroud)

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

  • 问题被标记为osx,因此代码适用于Mac.在iOS上,您将使用`UIBezierPath`,`UIColor`和`CGPoint`而不是`NSBezierPath`,`NSColor`和`NSPoint`(您也可以在两个平台上使用较低级别的Core Graphics功能). (4认同)

Swi*_*ect 5

iOS + 斯威夫特

(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()
    }
}
Run Code Online (Sandbox Code Playgroud)

(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()
}
Run Code Online (Sandbox Code Playgroud)