2011-07-10 94 views
4

我想是這樣的:(光部分,忽略背景)如何使用Core Graphics繪製三角形 - Mac?

example triangle

我如何可以得出這樣的使用可可?在drawRect:?我不知道如何畫畫。

+2

如果你「不知道怎麼畫」,你應該閱讀其中一個或兩個:http://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/ http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaDrawingGuide/ –

回答

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]; 
} 

這應該讓你開始,它借鑑了100×100大小的視圖中的紅色三角形。您通常會根據視圖的大小動態計算座標,而不是使用硬編碼的值。

+0

比我想象的要容易得多。謝謝! – Names

+0

哈!讓我想起了標誌中的烏龜。 – Timo

+0

是不是[UIColor redColor] setFill]和CGPointMake? NSMakePoint和CGPointMake有什麼不同? – futurevilla216

3

的iOS +斯威夫特

(1)創建一個斯威夫特擴展

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