[英]Draw a semi-circle button iOS
我正在嘗試繪制一個半圓形按鈕。 我在繪制半圓並將其附加到我在 xcode 中制作的按鈕上都遇到了麻煩。 xcode 中的按鈕具有將其固定到屏幕底部並將其居中的約束。 我在視圖控制器中引用按鈕,然后嘗試將其覆蓋為半圓,如下所示。 我得到一個空白按鈕。 我還在按鈕所在的故事板的坐標中進行了硬編碼。 有沒有更好的方法來做到這一點?
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: 113.0, y: 434.0),
radius: 10.0, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.CGPath
sunButton.layer.mask = circleShape
問題是您的形狀圖層位於按鈕邊界之外。 如果您只是將形狀圖層添加為按鈕圖層的子視圖,您將看到問題:
button.layer.addSublayer(circleShape)
您必須調整弧中心點,使弧位於按鈕的邊界內:
let circlePath = UIBezierPath.init(arcCenter: CGPointMake(button.bounds.size.width / 2, 0), radius: button.bounds.size.height, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.CGPath
button.layer.mask = circleShape
你會得到這個:
斯威夫特 5 更新:
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: button.bounds.size.width / 2, y: 0), radius: button.bounds.size.height, startAngle: 0.0, endAngle: .pi, clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
button.layer.mask = circleShape
斯威夫特 5:
// semiCircleDown
let circlePath = UIBezierPath(arcCenter: CGPoint(x: shapeView.bounds.size.width/2, y: 0), radius: shapeView.bounds.size.height, startAngle: 0, endAngle: .pi, clockwise: true).cgPath
//semiCircleUp
let circlePath = UIBezierPath(arcCenter: CGPoint(x: shapeView.bounds.size.width/2, y: 0), radius: shapeView.bounds.size.height, startAngle: 2 * .pi, endAngle: .pi, clockwise: true).cgPath
//quarterCircleRightDown
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0), radius: shapeView.bounds.size.width, startAngle: 2 * .pi, endAngle: .pi * 3/2, clockwise: true).cgPath
//quarterCircleLeftDown
let circlePath = UIBezierPath(arcCenter: CGPoint(x: shapeView.bounds.size.width, y: 0), radius: shapeView.bounds.size.width, startAngle: .pi * 3/2, endAngle: .pi, clockwise: true).cgPath
quarterCircleRightUp
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 0, y: shapeView.bounds.size.height), radius: shapeView.bounds.size.width, startAngle: 0, endAngle: .pi/2, clockwise: false).cgPath
//quarterCircleLeftUp
let circlePath = UIBezierPath(arcCenter: CGPoint(x: shapeView.bounds.size.width, y: shapeView.bounds.size.height), radius: shapeView.bounds.size.width, startAngle: .pi/2, endAngle: .pi, clockwise: false).cgPath
let shape = CAShapeLayer()
shape.path = circlePath.cgPath
shapeView.layer.mask = shape
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.