ZSWRoundedImage is an extension of UIImage
for creating resizable images with any of the corners rounded. This library does not yet work with Objective-C as it's part of the application I'm writing to learn Swift.
You may be asking yourself, "why not round the CALayer
instead of setting a background image?" This requires clipping the contents and adds transparency, both of which hurt performance. Using a background image allows creating fully opaque views while preserving the visual impact of rounded corners.
This adds a single public method to UIImage:
extension UIImage {
public static func imageWithRoundedCorners(
roundedCorners: UIRectCorner,
cornerRadius: CGFloat,
resizingDirection: RoundedResizingDirection,
foregroundColor: UIColor,
backgroundColor: UIColor,
borderColor: UIColor? = default,
borderWidth: CGFloat? = default
) -> UIImage
}
To start, import the library:
import ZSWRoundedImage
and set the image in a UIImageView
:
imageView.image = UIImage.imageWithRoundedCorners(
.AllCorners, cornerRadius: 10.0,
resizingDirection: .Both,
foregroundColor: UIColor.blackColor(),
backgroundColor: UIColor.clearColor()
)
A common design requirement is a background that looks like a pill. You create this by specifying a cornerRadius
equal to half the height of your display. By default, this library adds a tiling pixel so the image can resize in any direction; this tiling pixel throws off the clean circular look of the pill. To eliminate this tiling pixel, pass either .Horizontal
or .Vertical
for the resizing direction, and it will not include one.
Good question, curious explorer! This is not an init method because creating a resizable UIImage
requires a combination of initialization and copying-again-with-arguments. Swift init methods cannot change the return value or assign to self, so as of at least Swift 2.0 this is not possible. This was filed as 23128341.
The pursuit of clean edges and retina images. The system-provided rounding rectangle function for UIBezierPath is very badly anti-aliased because it draws at non-integral point locations. This library's primary purpose is to draw extremely clean lines, and so a custom path was necessary.
ZSWRoundedImage is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "ZSWRoundedImage", "~> 1.0"
ZSWRoundedImage is available under the MIT license. See the LICENSE file for more info.