如何在Swift中将特定的CGPoint设置为UIImageView的中心?

问题描述 投票:0回答:4

我有一个特定的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)
}
ios swift core-graphics core-image
4个回答
1
投票

这样做:

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)
}

0
投票

你可以这样做:

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)

0
投票

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

layer.positionanchorPoint相关,imgPreViewOutlet.addSubview(firstDotView!) 默认为图层内容的中心。


0
投票

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

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

更换

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

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.