UIImage Aspect Fit when using drawInRect?

后端 未结 6 1186
囚心锁ツ
囚心锁ツ 2020-12-13 18:51

UIView provides for the \"aspect fit\" content mode. However, I\'ve subclasses UIView and would like to draw a UIImage using drawInRect with an aspect fit. Is there any way

6条回答
  •  一整个雨季
    2020-12-13 19:22

    here's the solution

    CGSize imageSize = yourImage.size;
    CGSize viewSize = CGSizeMake(450, 340); // size in which you want to draw
    
    float hfactor = imageSize.width / viewSize.width;
    float vfactor = imageSize.height / viewSize.height;
    
    float factor = fmax(hfactor, vfactor);
    
    // Divide the size by the greater of the vertical or horizontal shrinkage factor
    float newWidth = imageSize.width / factor;
    float newHeight = imageSize.height / factor;
    
    CGRect newRect = CGRectMake(xOffset,yOffset, newWidth, newHeight);
    [image drawInRect:newRect];
    

    -- courtesy https://stackoverflow.com/a/1703210

    another alternative for aspect fit

    -(CGSize ) getImageSize :(CGSize )imgViewSize andActualImageSize:(CGSize )actualImageSize {
    
         // imgViewSize = size of view in which image is to be drawn
         // actualImageSize = size of image which is to be drawn
    
         CGSize drawImageSize;
    
         if (actualImageSize.height > actualImageSize.width) {
    
            drawImageSize.height = imgViewSize.height;
            drawImageSize.width = actualImageSize.width/actualImageSize.height * imgViewSize.height;
    
         }else {
    
            drawImageSize.width = imgViewSize.width;
            drawImageSize.height = imgViewSize.width * actualImageSize.height /  actualImageSize.width;
         }
         return drawImageSize;
    }
    

    Code for swift 3.0:

    func getAspectFitFrame(sizeImgView:CGSize, sizeImage:CGSize) -> CGRect{
    
        let imageSize:CGSize  = sizeImage
        let viewSize:CGSize = sizeImgView
    
        let hfactor : CGFloat = imageSize.width/viewSize.width
        let vfactor : CGFloat = imageSize.height/viewSize.height
    
        let factor : CGFloat = max(hfactor, vfactor)
    
        // Divide the size by the greater of the vertical or horizontal shrinkage factor
        let newWidth : CGFloat = imageSize.width / factor
        let newHeight : CGFloat = imageSize.height / factor
    
        var x:CGFloat = 0.0
        var y:CGFloat = 0.0
        if newWidth > newHeight{
            y = (sizeImgView.height - newHeight)/2
        }
        if newHeight > newWidth{
            x = (sizeImgView.width - newWidth)/2
        }
        let newRect:CGRect = CGRect(x: x, y: y, width: newWidth, height: newHeight)
    
        return newRect
    
    }
    

提交回复
热议问题