10月 03, 2017

『Swift』用UIBezierPath與CAShapeLayer畫直線與圓


這裡教大家使用Path跟Layer來畫畫

直線與圓形範例如下:


畫直線:
//宣告Path與Layer
var mLinePath = UIBezierPath()
var mLineShapeLayer = CAShapeLayer()

//設置起點與下一個點
mLinePath.removeAllPoints()
mLinePath.move(to: CGPoint(x: 0 ,y: 0 ))
mLinePath.addLine(to: CGPoint(x: 100 ,y: 100))
//這裡說起點與下一個點的的意思是
//你可以一直addLine下去,他就會變成多點連線

//把path綁到Layer上,設置線的顏色跟寬度
mLineShapeLayer.path = mLinePath.cgPath
mLineShapeLayer.strokeColor = UIColor(red: 0,green: 0,blue: 0,alpha: 1).cgColor
mLineShapeLayer.lineWidth = 1.0

//加到view上面
self.view.layer.addSublayer(mLineShapeLayer)

畫圓:
//宣告Path與Layer
var mCirclePath = UIBezierPath()
var mCircleShapeLayer = CAShapeLayer()
var mCenter: CGPoint!
var mRadius: CGFloat!
let mStartAngle: CGFloat = 0.0
let mEndAngle: CGFloat = CGFloat(2 * M_PI)

mCenter = CGPoint!(x: 100, y: 100)
//設定原點
mRadius = 10.0
//設定半徑
mCirclePath = UIBezierPath(arcCenter: mCenter, radius: mRadius, startAngle: mStartAngle, endAngle: mEndAngle, clockwise: true)
//畫圓

//把path綁到Layer上
mCircleShapeLayer.path = mCirclePath.cgPath
mCircleShapeLayer.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
//設定填滿的顏色
mCircleShapeLayer.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
//設定邊的顏色
mCircleShapeLayer.lineWidth = 1.0
//設定邊的寬度

//加到view上面
self.view.layer.addSublayer(mCircleShapeLayer)


沒有留言:

Related Posts Plugin for WordPress, Blogger...