【问题标题】:How do I create a circle with CALayer?如何使用 CALayer 创建一个圆圈?
【发布时间】:2015-02-28 15:39:43
【问题描述】:

我已经测试了下面的代码,但是当我给它限制时,它变成了一个小圆圈:

 override func drawRect(rect: CGRect) {
var path = UIBezierPath(ovalInRect: rect)
fillColor.setFill()
path.fill()

//set up the width and height variables
//for the horizontal stroke
let plusHeight:CGFloat = 300.0
let plusWidth:CGFloat = 450.0

//create the path
var plusPath = UIBezierPath()

//set the path's line width to the height of the stroke
plusPath.lineWidth = plusHeight

//move the initial point of the path
//to the start of the horizontal stroke
plusPath.moveToPoint(CGPoint(
  x:self.bounds.width/2 - plusWidth/2 + 0.5,
  y:self.bounds.height/2 + 0.5))

//add a point to the path at the end of the stroke
plusPath.addLineToPoint(CGPoint(
  x:self.bounds.width/2 + plusWidth/2 + 0.5,
  y:self.bounds.height/2 + 0.5))

}

【问题讨论】:

  • 尝试将其放入 viewDidAppear

标签: swift calayer


【解决方案1】:

根据需要更改半径和填充颜色。 :)

import Foundation
import UIKit

class CircleLayerView: UIView {
    var circleLayer: CAShapeLayer!

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        if circleLayer == nil {
            circleLayer = CAShapeLayer()
            let radius: CGFloat = 150.0
            circleLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2.0 * radius, height: 2.0 * radius), cornerRadius: radius).cgPath
            circleLayer.position = CGPoint(x: self.frame.midX - radius, y: self.frame.midY - radius)
            circleLayer.fillColor = UIColor.blue.cgColor
            self.layer.addSublayer(circleLayer)
        }
    }
}

【讨论】:

  • 吹毛求疵,但这里不需要调用 super,因为你是 UIView 的子类:stackoverflow.com/a/26479578/3128245
  • 另外,为了避免使 circleLayer 成为隐式展开的可选 (CAShapeLayer!),您可以实例化 let circleLayer = CAShapeLayer() 并防止它在 drawRect 中有一个带有 guard circleLayer.superlayer == nil else { return } 的超级层
  • 我忘记了它是哪个 WWDC 会议,但 Apple 说你不应该在 drawRect 中添加图层。这是有道理的。相反,在视图布局完成后设置图层,配置它们,然后让渲染系统自动处理它们
【解决方案2】:

传入drawRectrect 是需要更新的区域,而不是绘图的大小。在您的情况下,您可能会忽略传入的矩形并将圆圈设置为您想要的大小。

    //// Oval Drawing
    var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 300, 300))
    UIColor.whiteColor().setFill()
    ovalPath.fill()

【讨论】:

  • 这应该是公认的答案。 ovalInRect 是正确的方法。其他只是解决方法
猜你喜欢
  • 1970-01-01
  • 2019-07-19
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多