根据选取的图像(从图像选择器)更改图像视图框架SWIFT

时间:2019-03-03 07:38:39

标签: swift image imageview frames

我有一个图像视图,其中有一个设置的框架,但是当用户单击它并更改图像(UIImagePickerController)时,我就需要以某种方式将图像视图的框架更改为图像的框架。

当他们单击其图像的选择按钮时,这就是我运行的代码。

$servername = "<The IP address from the overview page of Cloud SQL>";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

所以图像出现在图像视图中,但是我需要一些帮助,以找到一种方法来使图像视图框架更改为拾取的图像框架。

这是框架不变的意思。

Frame Not Changing

谢谢

2 个答案:

答案 0 :(得分:0)

首先,您应该使用以下方法获取AspectFitSize:

public func getAspectFitFrame(from: CGSize, to: CGSize) -> (CGRect, CGFloat) {
    let (hfactor, vfactor, factor) = getFactor(from: from, to: to)

    let newWidth = to.width / factor
    let newHeight = to.height / factor

    var x: CGFloat = 0.0
    var y: CGFloat = 0.0

    if hfactor > vfactor {
        y = (from.height - newHeight) / 2
    } else {
        x = (from.width - newWidth) / 2
    }
    return (CGRect(x: x, y: y, width: newWidth, height: newHeight), factor)
}

public func getFactor(from: CGSize, to: CGSize) -> (CGFloat, CGFloat, CGFloat) {
    let hfactor = to.width / from.width
    let vfactor = to.height / from.height
    return (hfactor, vfactor, max(hfactor, vfactor))
}

之后,您应该使用newSize修改imageViewSize:

let (imageFitSize , _) = getAspectFitFrame(from : self.itemImage.frame.size , to : self.itemImage.image.size)
self.image.frame.size = imageFitSize.size

答案 1 :(得分:0)

在我看来,您的imageView已经应用了一些约束。我建议对其应用大小限制。

// declare these at the top of the file so that the constraints can be removed when new images are selected
private var widthConstraint: NSLayoutConstraint?
private var heightConstraint: NSLayoutConstraint?

// remove old constraint
widthConstraint?.isActive = false
// fix the imageview width to that of the picked image
widthConstraint = itemImage.widthAnchor.constraint(equalToConstant: pickedImage.size.width)
widthConstraint?.isActive = true

heightConstraint?.isActive = false
heightConstraint = itemImage.heightAnchor.constraint(equalToConstant: pickedImage.size.height)
heightConstraint?.isActive = true