crispy2k12 crispy2k12 - 2 months ago 7x
Swift Question

Rounding corners of images in an array xcode

I'm attempting to round the corners of images that are stored within an array, but i'm not entirely sure if its possible?

var holeImages = [UIImage(named:"1.png"),UIImage(named:"2.png"),UIImage(named:"3.png")]

self.holeImages1.layer.cornerRadius = 10.0f;

Rob Rob

You probably want to just apply a corner radius to the layer of the UIImageView in which you present the images, rather than rounding the images themselves, e.g.

imageView.layer.cornerRadius = 10

But if you really want to round the images, themselves, rather than rounding the UIImageView in which you present the images, you could also build a new array of rounded images from your holeImages array:

let roundedHoleImages = { return $0?.rounded(cornerRadius: 10) }

Where you could round the images with something like:

extension UIImage {

    /// Round the corners of an image
    /// - parameter cornerRadius: The `CGFloat` corner radius to apply to the images.
    /// - returns: The rounded image.

    func rounded(cornerRadius cornerRadius: CGFloat) -> UIImage? {
        let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height), cornerRadius: cornerRadius)

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        CGContextAddPath(context, path.CGPath)
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()

        return outputImage


You might use this rounding of the actual images if you were, for example, uploading the images to some web service and you wanted to upload images with rounded corners. But, if not, rounding the image views is not only easier, but avoids problems resulting from images of different scales (especially if those scales are different from the display scale) as well as minimizing the memory impact of creating a separate array of images.