我正在尝试在Xcode 8,Swift 3上的UIView子类中绘制一个蓝色圆圈。在一个Cocoa Touch文件中,我用作Storyboard中View对象的类,我写了下面的代码,但是圆圈未显示:
import UIKit
class testView: UIView {
override func draw(_ layer: CALayer, in ctx: CGContext) {
ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))
ctx.setFillColor(UIColor.blue.cgColor)
ctx.fillPath()
}
}
这个版本与UIKit
不显示圆圈:
override func draw(_ layer: CALayer, in ctx: CGContext) {
UIGraphicsPushContext(ctx)
let p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
UIColor.blue.setFill()
p.fill()
UIGraphicsPopContext()
}
我究竟做错了什么?
我正在处理你的问题,这是我的结果,首先你需要得到你的CurrentGraphicsContent,如果你不这样做,你不能画任何东西,所以试试这个代码
override func draw(_ rect: CGRect) {
super.draw(rect)
if let ctx = UIGraphicsGetCurrentContext() {
ctx.setFillColor(UIColor.blue.cgColor)
ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))
ctx.fillPath()
UIGraphicsEndImageContext()
}
// Drawing code
}
我希望这可以帮助你