我希望有类似这样的效果:(忽略背景,只看明亮部分)
如何使用Cocoa绘制这个图形?在
如何使用Cocoa绘制这个图形?在
drawRect:
中吗?我不知道如何绘制。drawRect:
中吗?我不知道如何绘制。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大小的视图上绘制了一个红色三角形。当然,通常情况下,你会根据视图的大小动态计算坐标,而不是使用硬编码的值。
UIBezierPath
、UIColor
和 CGPoint
代替 NSBezierPath
、NSColor
和 NSPoint
(在两个平台上都可以使用更低级别的Core Graphics函数)。 - omzUIBezierPath
的addLineToPoint:(CGPoint)point)
选择器,而不是lineToPoint:(NSPoint)point)
。 - rolling_codes(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()
}
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()