我在两点之间绘制一条线,但视图上没有出现任何内容。我已经搜索了其他s / o问题,但似乎无法找到解决方案。
override func viewDidLoad() {
super.viewDidLoad()
self.drawLineFromPoint(point1: CGPoint(x: 10,y: 50), point2: CGPoint(x: 10,y: 80))
}
func drawLineFromPoint(point1:CGPoint, point2:CGPoint) {
let path = UIBezierPath()
path.move(to: point1)
path.addLine(to: point2)
let shapeLayer = CAShapeLayer()
shapeLayer.bounds = CGRect(x: 100, y: 100, width: 100, height: 100)
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.green.cgColor
shapeLayer.lineWidth = 3
shapeLayer.fillColor = UIColor.clear.cgColor
self.view.layer.addSublayer(shapeLayer)
}
答案 0 :(得分:1)
尝试此代码:在Swift 3中测试。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let shapeLayer = ShapeView(frame: CGRect(x: 100, y: 200, width: 100, height: 100), shape: 0)
shapeLayer.backgroundColor = UIColor.clear
shapeLayer.layer.borderWidth = 5
shapeLayer.layer.borderColor = UIColor.red.cgColor
view.addSubview(shapeLayer)
}
创建一个swift文件并在UIView类中将其命名为ShapeView.swift并添加以下代码。
import UIKit
class ShapeView: UIView {
var currentShapeType: Int = 0
init(frame: CGRect, shape: Int) {
super.init(frame: frame)
self.currentShapeType = shape
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
ctx?.beginPath()
ctx?.move(to: CGPoint(x: 10.0, y: 50.0))
ctx?.addLine(to: CGPoint(x: 10.0, y: 80.0))
// ctx?.addLine(to: CGPoint(x: 100.0, y: 200.0))
ctx?.setLineWidth(3)
ctx?.closePath()
ctx?.strokePath()
}
}
输出:
答案 1 :(得分:0)
您的问题似乎像我的:您忘了在行末添加这些行:
shapeLayer.stroke()
shapeLayer.fill()