UIImage Aspect Fit when using drawInRect?

后端 未结 6 1188
囚心锁ツ
囚心锁ツ 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:27

    The math for that is a little bit hairy, but fortunately, here's a solution I prepared earlier:

    - (UIImage *)imageScaledToSize:(CGSize)size
    {
        //create drawing context
        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    
        //draw
        [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
    
        //capture resultant image
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    - (UIImage *)imageScaledToFitSize:(CGSize)size
    {
        //calculate rect
        CGFloat aspect = self.size.width / self.size.height;
        if (size.width / aspect <= size.height)
        {
            return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)];
        }
        else
        {
            return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)];
        }
    }
    

    The first function is equivalent to "scale to fill", the second (which calls the first) is equivalent to "aspect fit". These methods were written as a category on UIImage so to use them from within another class you'll need to tweak them by passing the image in as a second parameter (or just make a category on UIImage like I did).

提交回复
热议问题