宽高比调整后从UIImageView获取图像的宽度和高度

时间:2018-11-25 09:25:14

标签: swift

在将图像缩放到适合宽高比之后,我试图从UIImageView获取图像的宽度和高度。这就是我得到宽度和高度的方式:

int compare(const void *a, const void *b)
{
int a1 = *static_cast<const int *>(a);
int b1 = *static_cast<const int *>(b);
if (a1 < b1)
    return -1;
if (a1 == b1)
    return 0;
return 1;
}

显然,这给了我宽度和高度。但是,在尝试将UIView调整为相同尺寸后,它们的尺寸不同。这是我将UIView设置为图像的宽度和高度的方法:

let imageHeight = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).height
let imageWidth = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).width

let imageYposition = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).origin.y
let imageXposition = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).origin.x

会发生这种情况:

This is what happens

1 个答案:

答案 0 :(得分:0)

尝试一下:

guard let image = imageView.image else { return }

// Calculate the scaled size of the image
let scaledRect = AVMakeRect(aspectRatio: image.size, insideRect: imageView.bounds)

// Create the overlay view
let overlayView = UIView(frame: .zero)
overlayView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
overlayView.translatesAutoresizingMaskIntoConstraints = false

// Add the overlay
// To use relate 2 views by auto-layout constraints, they must have the
// same parent view
imageView.superView!.addSubview(overlayView)
overlayView.widthAnchor.constraint(equalToConstant: scaledRect.width).isActive = true
overlayView.heightAnchor.constraint(equalToConstant: scaledRect.height).isActive = true
overlayView.centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
overlayView.centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true