I want something like this: (light part, ignore background)
How can I draw this 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.
(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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With