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

5
我希望有类似这样的效果:(忽略背景,只看明亮部分)
如何使用Cocoa绘制这个图形?在drawRect:中吗?我不知道如何绘制。

2
如果你“不知道如何绘画”,你应该阅读下列网址之一或者两个: http://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/ http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaDrawingGuide/ - Peter Hosey
3个回答

23
使用 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大小的视图上绘制了一个红色三角形。当然,通常情况下,你会根据视图的大小动态计算坐标,而不是使用硬编码的值。


比我想象中容易,谢谢! - Names
[UIColor redColor] setFill] 和 CGPointMake 不是一样的吗?NSMakePoint 和 CGPointMake 有什么区别吗? - futurevilla216
4
这个问题标记为osx,所以代码是针对Mac的。在iOS上,你需要使用 UIBezierPathUIColorCGPoint 代替 NSBezierPathNSColorNSPoint(在两个平台上都可以使用更低级别的Core Graphics函数)。 - omz
在iOS中,您还可以使用UIBezierPathaddLineToPoint:(CGPoint)point)选择器,而不是lineToPoint:(NSPoint)point) - rolling_codes

5

iOS + Swift

(1) 创建一个Swift扩展(extension)

// 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()
}

1
iOS + Swift5(更新上下文处理,允许使用不同宽度)。
        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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接