Swift:在自动布局中保留浮点小数

时间:2018-09-05 14:07:19

标签: swift

这是我的帖子here上的一个有问题的关注。我试图根据图像的大小动态地修复imageView的heightConstraint,然后在其上添加一个绘图层。但是,我注意到由于浮动点的划分,imageView的大小失去了精度,这在我开始在我的图像上绘画时导致图像模糊,即位图的放置不完全在覆盖原始图像的位置。

我的代码本身,用print语句观察小数位。

func setupViews() {
    view.backgroundColor = .black

    view.addSubview(canvasImageView)

    canvasImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    canvasImageView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
    canvasImageView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true

    let aspectRatio = getImageAspectRatio(image: image)
    let screenWidth = UIScreen.main.bounds.width
    let height = CGFloat(1.0) / CGFloat(aspectRatio)  * CGFloat(screenWidth)
    canvasImageView.heightAnchor.constraint(equalToConstant: height).isActive = true
    print("ImageSize", image.size.height)
    print("Aspect Ratio image at start:", aspectRatio)
    print("Calculated height:", height)


    DispatchQueue.main.async {
        print("Aspect Ratio imageView at start:", self.getAspectRatio(frame: self.canvasImageView.frame))
        print("ImageViewSize", self.canvasImageView.frame.height)

    }
}

我的打印报表在这里:

ImageSize 3000.0 2002.0  
Aspect Ratio image at start: 1.4985014985015 
Calculated height: 213.546666666667  
Aspect Ratio imageView at start: 1.49532710280374  
ImageViewSize 320.0 214.0

如您所见,我尝试执行heightAnchor.constraint(equalToConstant: height)实际上会失去精度,并导致分辨率降低。有办法消除这种情况吗?结果的图片在这里。

enter image description here

0 个答案:

没有答案