How to draw triangle using Core Graphics - Mac?
I want something like this: (light part, ignore background)
How can I draw th开发者_开发技巧is using Cocoa? In drawRect:
? I don't know how to draw.
Use 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];
}
This should get you started, it draws a red triangle on a 100x100 sized view. You'd usually calculate the coordinates dynamically, based on the view's size, instead of using hard-coded values of course.
iOS + Swift
(1) Create a 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) Override 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()
}
iOS + Swift5 (Updated Context handling, allow for diff widths)
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()
精彩评论