Skip to content

Instantly share code, notes, and snippets.

@toioski
Last active August 29, 2015 14:17
Show Gist options
  • Save toioski/0d2c01a44045cafd5cb4 to your computer and use it in GitHub Desktop.
Save toioski/0d2c01a44045cafd5cb4 to your computer and use it in GitHub Desktop.
Conversion to Swift of Barry Allard UIView+ClipBackgroundImageToBounds
//
// UIView+ClipBackgroundImageToBounds.m
//
// Created by Barry Allard on 2013-06-18.
// Copyright (c) 2013 Stealth Mode Industries LLC. All rights reserved.
//
// Based on http://stackoverflow.com/questions/262156/uiimage-rounded-corners
//
// MIT License
import UIKit
import QuartzCore
extension UIButton {
func setBackgroundImageClippedToBounds(image: UIImage?, forState state: UIControlState)-> Void {
if (!( !self.clipsToBounds && self.layer.cornerRadius != 0 )) {
self.setBackgroundImage(image, forState: state)
}
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 1.0)
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).addClip()
// Draw your image
image?.drawInRect(self.bounds)
// Get the image, here setting the UIImageView image
let clippedBackgroundImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
// Do what we came here to do
self.setBackgroundImage(clippedBackgroundImage, forState: state)
}
}
@skull-squadron
Copy link

Gold ⭐ :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment