使用Playgrounds在Swift中使用BezierPath

8

我需要创建一个自定义类才能在Swift playgrounds中使用BezierPath吗?

以下代码什么也不显示,只有黑色背景:

import UIKit
import XCPlayground

class GraphView : UIView {

    override func drawRect(rect: CGRect) {

        let path = UIBezierPath(rect: rect)
        path.moveToPoint(CGPointMake(0,0))
        path.addLineToPoint(CGPointMake(50,100))
        path.closePath()
        UIColor.redColor().setFill()

        path.stroke()
    }

}


let graphView = GraphView(frame: CGRectMake(0,0,960,640))

将视图的背景颜色设置为白色,你就能看到你的线条了。不过它是黑色的,而不是红色。请参阅https://dev59.com/yWEi5IYBdhLWcg3wZ7ka#34659468获取绝妙的技巧。 - Eric Aya
我正在使用Playgrounds! - john doe
是的,我知道你正在使用Playgrounds。看看我的答案。 - Eric Aya
3
你设定了填充颜色,但是只用了stroke。如果你想绘制描边,请调用UIColor.redColor().setStroke()。如果你想要填充颜色,使用UIColor.redColor().setFill()并调用fill而不是stroke - Rob
2个回答

11

你必须在代码末尾使用这个:

XCPlaygroundPage.currentPage.liveView = graphView

并打开Playground的“助手编辑器”以查看结果。

还要更改视图的背景颜色,因为它是黑色的...而你的代码行也是黑色的。;)


我已经成功运行了,但是左侧的助理编辑器仅显示“GraphView”,而不显示图形或呈现的输出。 - john doe
【我的Playground截图】(https://www.evernote.com/l/AFnk7PAzYtBNIKHvk2LITLvkUQg4x261xz4),右侧是助手面板。 - Eric Aya
2
Swift 3+:PlaygroundPage.current.liveView = graphView - Grubas

2

在Swift 5中:

import UIKit

class GraphView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        let path = UIBezierPath(rect: rect)
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 50, y: 100))
        path.stroke()
    }

}

let graphView = GraphView(frame: CGRect(x: 0, y: 0, width: 960, height: 640))

playground中的视图截图 Swift 5.2,Xcode 11.4


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