-
-
Save kwigbo/47a918adfefc956eed40 to your computer and use it in GitHub Desktop.
This code snippet shows how to easily generate images at runtime for use in a button. This concept can be use in a variety of ways to reduce the amount of image assets need in an app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -- Create the button | |
testButton_ = [UIButton buttonWithType:UIButtonTypeCustom]; | |
[testButton_ setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; | |
testButton_.contentEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0); | |
[testButton_ setBackgroundImage:[self buttonImageExample] forState:UIControlStateNormal]; | |
[testButton_ setTitle:@"Test Button" forState:UIControlStateNormal]; | |
testButton_.translatesAutoresizingMaskIntoConstraints = NO; | |
[view addSubview:testButton_]; | |
- (UIImage *)buttonImageExample | |
{ | |
// -- Setup a few sizes needed to generate the stretchable image | |
CGSize imageSize = CGSizeMake(20.0, 20.0); | |
CGFloat halfSize = ceilf(imageSize.width/2.0); | |
// -- Start an image context, all drawing after this call will go to that context | |
[UIImage beginImageContextWithSize:imageSize]; | |
// -- Start Custom Drawing Code | |
CGRect drawRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height); | |
[UIView drawRect:drawRect withFillColor:[UIColor colorWithHex:0xff66CCFF]]; | |
CGRect insetRect = CGRectMake(1.0, 1.0, drawRect.size.width - 2.0, drawRect.size.height - 2.0); | |
[UIView drawRect:insetRect withFillColor:[UIColor whiteColor]]; | |
CGPathRef clipPath = [UIView newPathWithRect:insetRect]; | |
[UIView startClipToPath:clipPath]; | |
CGRect gradientRect = CGRectMake(insetRect.origin.x, insetRect.origin.y, insetRect.size.width, 4.0); | |
[UIView drawVerticalGradientWithStartColor:[UIColor colorWithHex:0x4466CCFF] endColor:[UIColor colorWithHex:0x0066CCFF] inRect:gradientRect]; | |
[UIView endClipToPath:clipPath]; | |
// -- End Custom Drawing Code | |
// -- Setup insets to make the image stretchable. | |
UIEdgeInsets stretchInsets = UIEdgeInsetsMake(imageSize.height - 5.0, | |
halfSize - 1.0, | |
imageSize.height - 3.0, | |
halfSize - 1.0); | |
// -- End the image context and return the resulting image. | |
// -- This image can be stored so as to only create the asset once. | |
return [[UIImage endImageContext] | |
resizableImageWithCapInsets:stretchInsets | |
resizingMode:UIImageResizingModeStretch]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment