How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

后端 未结 16 2492
不思量自难忘°
不思量自难忘° 2020-11-27 10:27

I have a bunch of images I am using for cell\'s image views, they are all no bigger than 50x50. e.g. 40x50, 50x32, 20x37 .....

When I load the table view, the tex

16条回答
  •  感情败类
    2020-11-27 10:46

    I've created an extension using @GermanAttanasio 's answer. It provides a method to resize an image to a desired size, and another method to do the same while adding a transparent margin to the image (this can be useful for table views where you want the image to have a margin as well).

    import UIKit
    
    extension UIImage {
    
        /// Resizes an image to the specified size.
        ///
        /// - Parameters:
        ///     - size: the size we desire to resize the image to.
        ///
        /// - Returns: the resized image.
        ///
        func imageWithSize(size: CGSize) -> UIImage {
    
            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale);
            let rect = CGRectMake(0.0, 0.0, size.width, size.height);
            drawInRect(rect)
    
            let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
    
            return resultingImage
        }
    
        /// Resizes an image to the specified size and adds an extra transparent margin at all sides of
        /// the image.
        ///
        /// - Parameters:
        ///     - size: the size we desire to resize the image to.
        ///     - extraMargin: the extra transparent margin to add to all sides of the image.
        ///
        /// - Returns: the resized image.  The extra margin is added to the input image size.  So that
        ///         the final image's size will be equal to:
        ///         `CGSize(width: size.width + extraMargin * 2, height: size.height + extraMargin * 2)`
        ///
        func imageWithSize(size: CGSize, extraMargin: CGFloat) -> UIImage {
    
            let imageSize = CGSize(width: size.width + extraMargin * 2, height: size.height + extraMargin * 2)
    
            UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale);
            let drawingRect = CGRect(x: extraMargin, y: extraMargin, width: size.width, height: size.height)
            drawInRect(drawingRect)
    
            let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
    
            return resultingImage
        }
    }
    

提交回复
热议问题