可能有超过5个问题,就像这个问题一样,但没有一个能解决问题。
我想在视图上居中一个圆圈。尽管通过像这样的类似问题尝试了各种方法,但这种情况并没有发生。
我不确定是否会发生这种情况,因为我设置了translatesAutoresizingMaskIntoConstraints = false
。我尝试使用形状图层的中心和锚点,但发生了疯狂的行为。我尝试将此代码放在viewDidLayouSubviews
中。没工作。我还能做什么?
colorSizeGuide
是我试图将我的图层集中在其中的视图。
func setupConstraints() {
// other constraints set up here
colorSizeGuide.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorSizeGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
colorSizeGuide.widthAnchor.constraint(equalToConstant: 30).isActive = true
colorSizeGuide.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
func setupColorSizeGuide() {
shape.path = UIBezierPath(ovalIn: colorSizeGuide.frame).cgPath
shape.position = self.colorSizeGuide.center
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shape.strokeColor = (UIColor.black).cgColor
shape.fillColor = (UIColor.clear).cgColor
shape.lineWidth = 1.0
colorSizeGuide.layer.addSublayer(shape)
}
答案 0 :(得分:1)
您可以选择几种方法。
tableView
),请使用视图上矩形宽度的一半的角半径,那么视图将被裁剪为圆形 - 这不是特别快或者可以自定义,但它可以完成工作。游乐场代码:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view: UIView = UIView(frame: frame)
view.backgroundColor = .magenta
view.layer.cornerRadius = frame.size.width / 2
PlaygroundPage.current.liveView = view
UIView
子类实现layerClass
方法并返回CAShapeLayer
。这意味着您的视图self.layer
实际上将是一个形状图层。您可以在那里设置圆圈的路径。如果要将其置于视图中心,请确保在定义UIBezierPath
时使用视图的边界坐标。游乐场代码:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view: UIView = UIView(frame: frame)
PlaygroundPage.current.liveView = view
class ShapeView: UIView {
override class var layerClass: AnyClass { return CAShapeLayer.self }
override init(frame: CGRect) {
super.init(frame: frame)
(layer as? CAShapeLayer)?.fillColor = UIColor.red.cgColor
(layer as? CAShapeLayer)?.strokeColor = UIColor.green.cgColor
(layer as? CAShapeLayer)?.path = UIBezierPath(ovalIn: frame).cgPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let sv = ShapeView(frame: frame)
view.addSubview(sv)
CAShapeLayer.init
制作非视图形状图层。使用layoutSubviews
方法(或viewDidLayoutSubviews
,如果您在视图控制器中执行此操作)定位您的视图,并为形状图层设置正确的框架,就像它是一个视图。{{3}}
游乐场代码:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let smallFrame: CGRect = CGRect(x: 0, y: 0, width: 10, height: 10)
let view: UIView = UIView(frame: frame)
view.backgroundColor = .magenta
PlaygroundPage.current.liveView = view
let sl = CAShapeLayer()
sl.path = UIBezierPath(ovalIn: smallFrame).cgPath
sl.fillColor = UIColor.red.cgColor
sl.strokeColor = UIColor.green.cgColor
sl.frame.origin.x = 30
sl.frame.origin.y = 30
view.layer.addSublayer(sl)