How to make UIImageView automatically resize to the size of the image loaded

后端 未结 2 430
天命终不由人
天命终不由人 2020-12-05 03:23

I have put an UIImageView control on my view with IB. The size of the control is just something I decided upon, pretty random size really What I want to do is the control to

2条回答
  •  鱼传尺愫
    2020-12-05 03:39

    Here is the code snippet I cut and paste often, using the same method as Hampus Nilsson above -

    Example

    func demo(x0:CGFloat, y0:CGFloat) {
        let imgView = UIImageView(image: UIImage(named: "someImg.png"));
        imgView.sizeToImage();
        imgView.center = CGPoint(x:x0, y:y0);
    }
    

    UIImageView Extension

    extension UIImageView {
    
    /******************************************************************************/
    /** @fcn        sizeToImage()
     *  @brief      size view to image
     *  @@assum     (image!=nil)
     */
    /******************************************************************************/
    func sizeToImage() {
    
        //Grab loc
        let xC = self.center.x;
        let yC = self.center.y;
    
        //Size to fit
        self.frame  = CGRect (x: 0, y: 0, width: (self.image?.size.width)!/2, height: (self.image?.size.height)!/2);
    
        //Move to loc
        self.center = CGPoint(x:xC, y:yC);
    
        return;
    }
    

    A wonderful cut & paste, use if needed!

提交回复
热议问题