当我在图像上绘图时,图像会放大

时间:2016-01-05 05:22:09

标签: ios swift uiview drawing

imageView就是照片。我创建了一张名为tempImageView的照片副本,我试图在tempImageView上绘图。但是,当我尝试绘制tempImageView时,它会放大以填满整个屏幕。

func createTempImageView(){
    tempImageView = UIImageView(frame:CGRect(x: 0, y: 0, width: imageView.image!.size.width, height: imageView.image!.size.height))
    tempImageView.center = CGPoint(x: imageView.center.x, y: imageView.center.y)
    view.insertSubview(tempImageView, aboveSubview: imageView)
}

1 个答案:

答案 0 :(得分:0)

因为我设置了imageView.contentMode = .ScaleAspectFit,所以屏幕上的图像的宽度和高度都比原始图像小。但是,imageView.image!.size.widthimageView.image!.size.height是指原始图片。因此,当我尝试在tempImageView上绘图时,图像被放大,因为tempImageView引用的原始图像比屏幕上的图像大得多。

要获取屏幕上图像的尺寸并停止放大图像,我这样做了:

func createTempImageView(){
    let widthRatio = imageView.bounds.size.width / imageView.image!.size.width
    let heightRatio = imageView.bounds.size.height / imageView.image!.size.height
    let scale = min(widthRatio, heightRatio)
    let imageWidth = scale * imageView.image!.size.width
    let imageHeight = scale * imageView.image!.size.height

    tempImageView = UIImageView(frame:CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
    tempImageView.center = CGPoint(x: imageView.center.x, y: imageView.center.y)
    tempImageView.backgroundColor = UIColor.clearColor()
    view.insertSubview(tempImageView, aboveSubview: imageView)
}