Swift如何设置一个特定的CGPoint作为UIImageView的中心?

How to set a specific CGPoint as the centre of UIImageView in Swift?

我有一个特定的 CGPoint,我希望我的 UIImageView 以它为中心。我不知道该怎么做。以下是我的尝试:

var firstDotView: UIView?
let dotSize: CGFloat = 20
@IBOutlet weak var imgPreViewOutlet: UIImageView!

override func viewDidLoad(){

    firstDotView = UIView.init()
    firstDotView?.frame = CGRect.init(x: 60, y: 60, width: dotSize, height: dotSize)
    firstDotView?.center = CGPoint.init(x: 60, y: 60)

    drawFirstDot()
    imgPreViewOutlet.addSubview(firstDotView!)

} 


// DRAW ROUND CIRCLE
func drawFirstDot() -> Void {
    let layer = CAShapeLayer.init()
    layer.path = UIBezierPath.init(roundedRect: firstDotView!.bounds, cornerRadius: 50).cgPath
    layer.fillColor = UIColor.blue.cgColor
    layer.backgroundColor = UIColor.yellow.cgColor
    firstDotView?.layer.addSublayer(layer)
}

这样做:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let firstDotView = UIView(frame: CGRect(x: imgPreViewOutlet.bounds.width/2 - dotSize/2,
                                            y: imgPreViewOutlet.bounds.height/2 - dotSize/2,
                                            width: dotSize,
                                            height: dotSize))
    firstDotView.layer.cornerRadius  = dotSize/2
    firstDotView.backgroundColor = UIColor.yellow
    firstDotView.translatesAutoresizingMaskIntoConstraints = false
    imgPreViewOutlet.addSubview(firstDotView)
}

你可以这样做:

let dotSize = 20
let firstDotView = UIView()
firstDotView.frame = CGRect(x: 0, y: 0, width: dotSize, height: dotSize)
firstDotView.backgroundColor = UIColor.black
firstDotView.layer.cornerRadius = 10
firstDotView.center = imageView.center

view.addSubview(firstDotView)

您也可以使用imageView.layer.position = CGPoint(x: 60, y: 60)

layer.position 是相对于 anchorPoint 的,默认情况下是图层内容的中心。

如果我没记错的话,你想在父视图的某处添加 firstDotView,然后将 imgPreViewOutlet 中心更改为与 firstDotView 中心相同。

首先将 firstDotView 作为子视图添加到父视图而不是 imgPreViewOutlet,然后将 imgPreViewOutlet 中心设置为等于 firstDotView 中心

替换

imgPreViewOutlet.addSubview(firstDotView!)

    view.addSubview(firstDotView!)
    imgPreViewOutlet.center = firstDotView!.centerde here