Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Category on UIButton to clip background image to background before setting it

View UIButton+ClipBackgroundImageToBounds.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
//
// 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 "UIButton+ClipBackgroundImageToBounds.h"
 
@implementation UIButton (ClipBackgroundImageToBounds)
- (void)setBackgroundImageClippedToBounds:(UIImage *)image forState:(UIControlState)state
{
if (!( ! self.clipsToBounds && self.layer.cornerRadius != 0.0f )) {
// Nothing special to do
[self setBackgroundImage:image forState:state];
return;
}
// 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, NO, 1.0);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:self.bounds
cornerRadius:self.layer.cornerRadius] addClip];
 
// Draw your image
[image drawInRect:self.bounds];
// Get the image, here setting the UIImageView image
UIImage* clippedBackgroundImage = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
// Do what we came here to do
[self setBackgroundImage:clippedBackgroundImage forState:state];
}
@end
View UIButton+ClipBackgroundImageToBounds.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
// UIView+ClipBackgroundImageToBounds.h
//
// 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/UIKit.h>
#import <QuartzCore/QuartzCore.h>
 
@interface UIButton (ClipBackgroundImageToBounds)
- (void)setBackgroundImageClippedToBounds:(UIImage *)image forState:(UIControlState)state;
@end
Owner

This probably should be refactored as a category on UIView, and then one category for each control.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.