Animate position of inner shadow - ios

I want to animate the position of an inner shadow on a bezier I created using PaintCode. The offset of the shadow will be animated, here's two examples:
How can I make this an animatable property so that I can animate the movement of the shadow? The generated code (pasted into drawRect) looks like this:
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Color Declarations
UIColor* fillColor = [UIColor colorWithRed: 1 green: 1 blue: 1 alpha: 1];
UIColor* strokeColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 0.508];
//// Shadow Declarations
UIColor* shadow = strokeColor;
CGSize shadowOffset = CGSizeMake(3.1, 3.1);
CGFloat shadowBlurRadius = 5;
//// Oval Drawing
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(31.5, 33.5, 26, 26)];
[fillColor setFill];
[ovalPath fill];
////// Oval Inner Shadow
CGRect ovalBorderRect = CGRectInset([ovalPath bounds], -shadowBlurRadius, -shadowBlurRadius);
ovalBorderRect = CGRectOffset(ovalBorderRect, -shadowOffset.width, -shadowOffset.height);
ovalBorderRect = CGRectInset(CGRectUnion(ovalBorderRect, [ovalPath bounds]), -1, -1);
UIBezierPath* ovalNegativePath = [UIBezierPath bezierPathWithRect: ovalBorderRect];
[ovalNegativePath appendPath: ovalPath];
ovalNegativePath.usesEvenOddFillRule = YES;
CGContextSaveGState(context);
{
CGFloat xOffset = shadowOffset.width + round(ovalBorderRect.size.width);
CGFloat yOffset = shadowOffset.height;
CGContextSetShadowWithColor(context,
CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)),
shadowBlurRadius,
shadow.CGColor);
[ovalPath addClip];
CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(ovalBorderRect.size.width), 0);
[ovalNegativePath applyTransform: transform];
[[UIColor grayColor] setFill];
[ovalNegativePath fill];
}
CGContextRestoreGState(context);
[strokeColor setStroke];
ovalPath.lineWidth = 1;
[ovalPath stroke];

Related

How to Convert CAShapeLayer to CAGradientLayer?

my code of making CAShapeLayer is
UIBezierPath *circle = [UIBezierPath bezierPathWithArcCenter:CGPointMake(75, 125)
radius:50
startAngle:0
endAngle:1.8 * M_PI
clockwise:YES];
CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setFrame:CGRectMake(200 - 50, 300 - 50, 100, 100)];
circleLayer.path = circle.CGPath;
circleLayer.bounds = CGPathGetBoundingBox(circle.CGPath);
circleLayer.strokeColor = [UIColor colorWithRed:0.4 green:1.0 blue:0.2 alpha:0.5].CGColor;
[circleLayer setFillColor:[UIColor clearColor].CGColor];
circleLayer.lineWidth = 3.0;
if ([circleLayer animationForKey:#"SpinAnimation"] == nil) {
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat: 2 * M_PI];
animation.duration = 2.0f;
animation.repeatCount = INFINITY;
animation.removedOnCompletion = NO;
[circleLayer addAnimation:animation forKey:#"SpinAnimation"];
}
[self.view.layer addSublayer:circleLayer];
I want to make CAGradientLayer instead of CAShapeLayer.
REASON: I need to use gradient color in layer, which is not possible in CAShapeLayer.
I want to use yellow to black gradient upon Cirle.
Image :
In my required output, color is fetched from background image, and put some black at the end, or opacity 0 within layer.
Any Idea, suggestion.
Thanks.
One quick and dirty trick is adding a gradient layer as a sublayer then put some more layers with the background colors same as the superview (in the original question, it's white).
For example:
Add a gradient layer (and set proper cornerRadius).
Add a smaller layer with white background color at the center of the gradient layer (this will create a ring).
Create a small segment of arc with white background color.
However, this may not be suitable views with background images.
To solve this, you can create a custom subclass of UIView and override the drawRect method.
Suppose there are instance variables: startColor, endColor, radius, strokeWidth, and mirrored.
The variable mirrored is used to control the position of the gap (cut off left side or right side) and the rotation direction of the animation (clockwise or counter-clockwise).
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
CGFloat gradientColors[4 * 2];
extractColorComponents(_startColor, gradientColors, 0);
extractColorComponents(_endColor, gradientColors, 4);
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, gradientColors, NULL, 2);
CGColorSpaceRelease(baseSpace);
baseSpace = nil;
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
gradient = nil;
// fill 'clear' color
CGContextSetFillColorWithColor(ctx, [UIColor clearColor].CGColor);
CGContextSetStrokeColorWithColor(ctx, [UIColor clearColor].CGColor);
CGContextSetBlendMode(ctx, kCGBlendModeClear);
CGFloat innerCircleRadius = _radius - _strokeWidth;
// fill an 'empty' hole inside the gradient part
CGContextFillEllipseInRect(ctx, (CGRect){
{_strokeWidth, _strokeWidth},
{innerCircleRadius * 2, innerCircleRadius * 2}
});
// fill an 'empty' segment of arc
CGFloat startAngle = _mirrored ? (0.9 * M_PI) : (-0.1 * M_PI);
CGFloat endAngle = startAngle + 0.2 * M_PI;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:(CGPoint){_radius, _radius}
radius:_radius - _strokeWidth * 0.5
startAngle:startAngle
endAngle:endAngle
clockwise:YES];
path.lineWidth = _strokeWidth;
CGContextAddPath(ctx, path.CGPath);
CGContextSetLineWidth(ctx, _strokeWidth + 2);
CGContextStrokePath(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
}
Here's the complete implementation of the view.
Final result:
Two rings:
You can add two rings in your viewDidLoad or somewhere else with the following code to achieve the desired effect:
- (void)viewDidLoad
{
[super viewDidLoad];
UIColor *startColor = [UIColor colorWithHue:0.02 saturation:0.74 brightness:0.91 alpha:1];
UIColor *endColor = [UIColor colorWithHue:0.57 saturation:0.76 brightness:0.86 alpha:1];
CGPoint center = CGPointMake(160, 200);
Spinner *outerSpinner = [[Spinner alloc] initWithCenter:center
radius:50
strokeWidth:3
startColor:startColor
endColor:endColor
mirrored:NO];
Spinner *innerSpinner = [[Spinner alloc] initWithCenter:center
radius:40
strokeWidth:3
startColor:startColor
endColor:endColor
mirrored:YES];
[self.view addSubview:outerSpinner];
[self.view addSubview:innerSpinner];
[outerSpinner startAnimating];
[innerSpinner startAnimating];
}
Result:
The mask property on CALayer uses the alpha component of the mask layer to determine what should be visible and not. Since both of your colors (black and white) are fully opaque (no transparency) the mask has no effect. To fix this you should change one of the colors to a clear color:
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor],
(id)[[UIColor clearColor] CGColor], nil];
EDIT
class Colors {
let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0).CGColor
let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0).CGColor
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}

UIBezierPath with color gradient

I've got an question about UIBezierPath.
For example I've got this path:
Now I want to have a color gradient from white to red. From left to right.
Here is my code:
UIBezierPath *bezierPath;
bezierPath = [UIBezierPath bezierPathWithArcCenter:_center radius:_radius startAngle:((4 * angle)) endAngle:(((20) * angle)) clockwise:YES];
[bezierPath addLineToPoint:_center];
[bezierPath closePath];
UIColor *color = [UIColor colorWithHue:0/sectors saturation:1. brightness:1. alpha:1];
[color setFill];
[color setStroke];
[bezierPath fill];
[bezierPath stroke];
Can anyone help me?
Edit 1:
I have this color wheel:
UIBezierPath *bezierPath;
for ( int i = 0; i < 360; i++) {
bezierPath = [UIBezierPath bezierPathWithArcCenter:_center radius:_radius startAngle:((i * angle)) endAngle:(((i + 1) * angle)) clockwise:YES];
[bezierPath addLineToPoint:_center];
[bezierPath closePath];
UIColor *color = [UIColor colorWithHue:i/sectors saturation:1. brightness:1. alpha:1];
[color setFill];
[color setStroke];
[bezierPath fill];
[bezierPath stroke];
}
but I want this: (With the white Gradient)
Use CAGradientLayer and mask it using CAShapeLayer Something like this
- (void)addCircle{
CAShapeLayer *shapeLayer = [CAShapeLayer new];
shapeLayer.path = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(10, 10, 100, 100), 4, 4)].CGPath;
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.contentsScale = [UIScreen mainScreen].scale;
shapeLayer.shouldRasterize = NO;
CAGradientLayer *_gradientLayer = [CAGradientLayer layer];
_gradientLayer.frame =self.view.bounds;
_gradientLayer.startPoint = CGPointMake(0.0, 1);
_gradientLayer.endPoint = CGPointMake(1, 0);
_gradientLayer.colors = #[(id)[UIColor blueColor].CGColor,(id)[UIColor redColor].CGColor];
//Add gradient layer to view
[self.view.layer addSublayer:_gradientLayer];
_gradientLayer.mask = shapeLayer;
}
Above method will add a triangle may be you need to change start and end points. Also you can change gradient values to whatever you need.
Apple Docs
CAGradientLayer Tutorial
Update After update its more clear that its not triangle you want, but what you need is possible with CAGradientLayer and CAShapeLayer, you need to follow same approach where you can add gradient with different colors and locations (stops)(if you are adding locations then make sure locations and colors are equal) and then mask it with CAShapeLayer which was circle.
you can give it a try :)
- (void)drawRect:(CGRect)rect
{
CGFloat arcStep = (M_PI *2) / 360; // M_PI*2 is equivalent of full cirle
BOOL clocklwise = NO;
CGFloat x = CGRectGetWidth(rect) / 2; // circle's center
CGFloat y = CGRectGetHeight(rect) / 2; // circle's center
CGFloat radius = MIN(x, y) / 2;
CGContextRef ctx = UIGraphicsGetCurrentContext();
// draw colorful circle
CGContextSetLineWidth(ctx, radius*2);
for (CGFloat i = 0; i < 360; i+=1)
{
UIColor* c = [UIColor colorWithHue:i/360 saturation:1. brightness:1. alpha:1];
CGContextSetStrokeColorWithColor(ctx, c.CGColor);
CGFloat startAngle = i * arcStep;
CGFloat endAngle = startAngle + arcStep + 0.02;
CGContextAddArc(ctx, x, y, radius, startAngle, endAngle, clocklwise);
CGContextStrokePath(ctx);
}
// drawing circles then, you might want few of them - smaller radius and less alpha with each step
UIColor* c = [[UIColor whiteColor] colorWithAlphaComponent: 0.03];
for (CGFloat fillRadius = radius/2; fillRadius > 0; fillRadius -= 1.f)
{
CGContextSetLineWidth(ctx, fillRadius*2);
CGContextSetStrokeColorWithColor(ctx, c.CGColor);
CGContextAddArc(ctx, x, y, fillRadius, 0, M_PI * 2, clocklwise);
CGContextStrokePath(ctx);
}
}
Another take on Oleg's answer regarding the saturation (white gradient) that I find more pleasing, and in Swift (3).
You can add steps to the gradient if you want a bigger white circle (ex a 2nd white step at 0.2)
import UIKit
class HSView: UIView {
override func draw(_ rect: CGRect) {
let arcStep = 2 * CGFloat.pi / 360
let isClockwise = false
let x = rect.width / 2
let y = rect.height / 2
let radius = min(x, y) / 2
let ctx = UIGraphicsGetCurrentContext()
ctx?.setLineWidth(2 * radius)
for i in 0..<360 {
let color = UIColor(hue: CGFloat(i)/360, saturation: 1, brightness: 1, alpha: 1)
let startAngle = CGFloat(i) * arcStep
let endAngle = startAngle + arcStep + 0.02
ctx?.setStrokeColor(color.cgColor)
ctx?.addArc(center: CGPoint(x: x, y: y), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: isClockwise)
ctx?.strokePath()
}
let gradient = CGGradient(colorsSpace: UIColor.white.cgColor.colorSpace,
colors: [
UIColor.white.cgColor,
UIColor.white.withAlphaComponent(0).cgColor,
] as CFArray,
locations: [
0,
1,
]
)
ctx?.drawRadialGradient(gradient!, startCenter: CGPoint(x: x, y: y), startRadius: 0, endCenter: CGPoint(x: x, y: y), endRadius: 2 * radius, options: .drawsAfterEndLocation)
}
}
You can try this:
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Shadow Declarations
NSShadow* shadow = [[NSShadow alloc] init];
[shadow setShadowColor: UIColor.whiteColor];
[shadow setShadowOffset: CGSizeMake(2.1, -4.1)];
[shadow setShadowBlurRadius: 5];
//// Bezier Drawing
UIBezierPath* bezierPath = UIBezierPath.bezierPath;
[UIColor.blackColor setStroke];
bezierPath.lineWidth = 1;
[bezierPath stroke];
//// Bezier 2 Drawing
UIBezierPath* bezier2Path = UIBezierPath.bezierPath;
[bezier2Path moveToPoint: CGPointMake(170.5, 59.5)];
[bezier2Path addCurveToPoint: CGPointMake(170.5, 71.5) controlPoint1: CGPointMake(173.5, 65.5) controlPoint2: CGPointMake(170.5, 71.5)];
[bezier2Path addLineToPoint: CGPointMake(155.5, 57.5)];
[bezier2Path addLineToPoint: CGPointMake(170.5, 59.5)];
[UIColor.redColor setFill];
[bezier2Path fill];
////// Bezier 2 Inner Shadow
CGContextSaveGState(context);
UIRectClip(bezier2Path.bounds);
CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL);
CGContextSetAlpha(context, CGColorGetAlpha([shadow.shadowColor CGColor]));
CGContextBeginTransparencyLayer(context, NULL);
{
UIColor* opaqueShadow = [shadow.shadowColor colorWithAlphaComponent: 1];
CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, [opaqueShadow CGColor]);
CGContextSetBlendMode(context, kCGBlendModeSourceOut);
CGContextBeginTransparencyLayer(context, NULL);
[opaqueShadow setFill];
[bezier2Path fill];
CGContextEndTransparencyLayer(context);
}
CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);
and the result will be:
You will archive it by using QuartsCore. If you want get image with your figure, you can call UIGraphicsBeginImageContext(), if you want draw it on UIView you should overload method - (void)drawRect:(CGRect)rect of UIView.
You can add path to context, and use it for clipping context (Don't forget save the context state before). After you can draw the gradient. The gradient will be clipped by path.
You will get something like this:
CGPathRef path = [bezierPath CGPath];
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSArray *colors = [NSArray arrayWithObjects:(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors( colorSpace, (CFArrayRef)colors, NULL);
CGColorSpaceRelease(colorSpace);
colorSpace = NULL;
CGContextDrawLinearGradient(context, gradient, CGPointMake(0.0, 0.0), CGPointMake(100.0, 100.0), kNilOptions);
CGContextRestoreGState(context);

UITabBarItem image created in code doesn’t appear

I create the following View in code, the idea is to use it as an image in UITableViewCell and UITabBarItem:
- (void)drawRect:(CGRect)rect
{
// Fill the background with white
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor * whiteColor = [UIColor colorWithRed:1.0
green:1.0
blue:1.0
alpha:1.0];
CGContextSetFillColorWithColor(context, whiteColor.CGColor);
CGContextFillRect(context, self.bounds);
//// Color Declarations
UIColor* fillColor = [UIColor colorWithRed: 1.0
green: 1.0
blue: 1.0
alpha: 1.0];
UIColor* strokeColor = [UIColor colorWithRed: 0.0
green: 0.0
blue: 0.0
alpha: 1.0];
//// Big Oval Drawing
CGRect bigOvalRect = CGRectMake(rect.origin.x+2,
rect.origin.y+5,
42.0,
42.0);
UIBezierPath* bigOvalPath = [UIBezierPath bezierPath];
[bigOvalPath addArcWithCenter: CGPointMake(CGRectGetMidX(bigOvalRect), CGRectGetMidY(bigOvalRect))
radius: CGRectGetWidth(bigOvalRect) / 2
startAngle: 40 * M_PI/180
endAngle: 320 * M_PI/180
clockwise: YES];
[fillColor setFill];
[bigOvalPath fill];
[strokeColor setStroke];
bigOvalPath.lineWidth = 1;
[bigOvalPath stroke];
}
To create an UIImage from this UIView I am using this code:
#import <QuartzCore/QuartzCore.h>
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Everything works as expected when I use it in my UITableViewCells but when I set it as the image of my UITabBarItem I only see a blue rectangle (iOS7):
MyIcon *icon = [[MyIcon alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
UIImage *tabImage =[self imageWithView:icon];
self.navigationController.tabBarItem.image = tabImage;
I guess it is something related with the alpha of the image but how can I fix it?
It wasn't a problem related to the size of the view but to its alpha.
I fixed it by setting the backgroundColor (was whiteColor) and the fillColor to:
[UIColor clearColor]
and by setting the view as opaque in the initWithFrame: method:
[self setOpaque = NO];

Adding inner shadow on uitextfield and uitextview

I am trying to add inner shadow on few UITextField and UITextView. I have set cornerRadius property for these controls to 1.0. and I am using the code which is mentioned below to create the inner shadow. But problem is that the shadow appears with the steep rectangular corners while the text view and the text field are with rounded corners.
I am calling following method in my viewcontroller class to add the shadow on my text field.
[self addInnerShadow:myTextField.frame];
- (void)addInnerShadow:(CGRect)frame
{
CAShapeLayer* shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:frame];
[shadowLayer setShadowColor:[[UIColor blackColor] CGColor]];
[shadowLayer setShadowOffset:CGSizeMake(0.0f, 0.0f)];
[shadowLayer setShadowOpacity:1.0f];
[shadowLayer setShadowRadius:5];
[shadowLayer setFillRule:kCAFillRuleEvenOdd];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectInset(CGRectMake(0, 0, frame.size.width, frame.size.height),-5, -5));
CGMutablePathRef someInnerPath = CGPathCreateMutable();
CGPathAddRect(someInnerPath, NULL, CGRectInset(CGRectMake(0, 0, frame.size.width, frame.size.height), 0, 0));
CGPathAddPath(path, NULL, someInnerPath);
CGPathCloseSubpath(path);
[shadowLayer setPath:path];
CGPathRelease(path);
CAShapeLayer* maskLayer = [CAShapeLayer layer];
[maskLayer setPath:someInnerPath];
[shadowLayer setMask:maskLayer];
[[self.view layer] addSublayer:shadowLayer];
}
This
CGContextRef context = UIGraphicsGetCurrentContext();
// Shadow
UIColor* shadow4 = [[UIColor blackColor] colorWithAlphaComponent: 0.81];
CGSize shadow4Offset = CGSizeMake(0.1, 2.1);
CGFloat shadow4BlurRadius = 5;
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(20.5, 26.5, 200, 40) cornerRadius: 4];
[[UIColor whiteColor] setFill];
[rectanglePath fill];
CGRect rectangleBorderRect = CGRectInset([rectanglePath bounds], -shadow4BlurRadius, - shadow4BlurRadius);
rectangleBorderRect = CGRectOffset(rectangleBorderRect, -shadow4Offset.width, - shadow4Offset.height);
rectangleBorderRect = CGRectInset(CGRectUnion(rectangleBorderRect, [rectanglePath bounds]), -1, -1);
UIBezierPath* rectangleNegativePath = [UIBezierPath bezierPathWithRect: rectangleBorderRect];
[rectangleNegativePath appendPath: rectanglePath];
rectangleNegativePath.usesEvenOddFillRule = YES;
CGContextSaveGState(context);
{
CGFloat xOffset = shadow4Offset.width + round(rectangleBorderRect.size.width);
CGFloat yOffset = shadow4Offset.height;
CGContextSetShadowWithColor(context,
CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)),
shadow4BlurRadius,
shadow4.CGColor);
[rectanglePath addClip];
CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(rectangleBorderRect.size.width), 0);
[rectangleNegativePath applyTransform: transform];
[[UIColor grayColor] setFill];
[rectangleNegativePath fill];
}
CGContextRestoreGState(context);
[[UIColor blackColor] setStroke];
rectanglePath.lineWidth = 0.5;
[rectanglePath stroke];
Will produce this. You can manipulate this to get your desired effect.
Create path with UIBezierPath
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:frame
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(5.0, 5.0)];
And than use it with Layer.

IOS 6 Custom UIView by paintcode

I am an IOS beginner.
I am trying to show a custom button with code generated by paintcode.
I drag a View on Storyboard then set this generic view class to my custom view "GreenButton". When I run the app, the button does not show up. I added NSLogs and could see the drawRect method worked successfully.
The code generated by paintcode seems to include everything to draw the button. I just use XCode to resize my view.
Do I need to implement initWithFrame method at all?
//
// GreenButton.m
// Test
//
// Created by Tim on 13.04.2013.
// Copyright (c) 2013 Tim. All rights reserved.
//
#import "GreenButton.h"
#implementation GreenButton
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// setup the initial properties of the view
}
return self;
}
#pragma mark - Touch event overrides
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
NSLog(#"drawRect enter");
//// General Declarations
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
//// Color Declarations
UIColor* strokeColor = [UIColor colorWithRed: 0.419 green: 0.434 blue: 0.455 alpha: 1];
UIColor* baseColor = [UIColor colorWithRed: 0.218 green: 0.24 blue: 0.268 alpha: 1];
CGFloat baseColorRGBA[4];
[baseColor getRed: &baseColorRGBA[0] green: &baseColorRGBA[1] blue: &baseColorRGBA[2] alpha: &baseColorRGBA[3]];
UIColor* upperColor = [UIColor colorWithRed: (baseColorRGBA[0] * 0.8 + 0.2) green: (baseColorRGBA[1] * 0.8 + 0.2) blue: (baseColorRGBA[2] * 0.8 + 0.2) alpha: (baseColorRGBA[3] * 0.8 + 0.2)];
UIColor* lowerColor = [UIColor colorWithRed: (baseColorRGBA[0] * 0.9) green: (baseColorRGBA[1] * 0.9) blue: (baseColorRGBA[2] * 0.9) alpha: (baseColorRGBA[3] * 0.9 + 0.1)];
UIColor* lightUpColor = [UIColor colorWithRed: (baseColorRGBA[0] * 0.5 + 0.5) green: (baseColorRGBA[1] * 0.5 + 0.5) blue: (baseColorRGBA[2] * 0.5 + 0.5) alpha: (baseColorRGBA[3] * 0.5 + 0.5)];
UIColor* lightDownColor = [UIColor colorWithRed: (baseColorRGBA[0] * 0.8) green: (baseColorRGBA[1] * 0.8) blue: (baseColorRGBA[2] * 0.8) alpha: (baseColorRGBA[3] * 0.8 + 0.2)];
//// Gradient Declarations
NSArray* buttonGradientColors = [NSArray arrayWithObjects:
(id)upperColor.CGColor,
(id)lowerColor.CGColor, nil];
CGFloat buttonGradientLocations[] = {0, 1};
CGGradientRef buttonGradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)buttonGradientColors, buttonGradientLocations);
NSArray* overlayGradientColors = [NSArray arrayWithObjects:
(id)lightUpColor.CGColor,
(id)[UIColor clearColor].CGColor, nil];
CGFloat overlayGradientLocations[] = {0, 1};
CGGradientRef overlayGradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)overlayGradientColors, overlayGradientLocations);
NSArray* gradientColors = [NSArray arrayWithObjects:
(id)lightUpColor.CGColor,
(id)lightDownColor.CGColor, nil];
CGFloat gradientLocations[] = {0, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);
//// Shadow Declarations
UIColor* buttonShadow = [UIColor blackColor];
CGSize buttonShadowOffset = CGSizeMake(0.1, 1.1);
CGFloat buttonShadowBlurRadius = 2;
UIColor* textShadow = [UIColor blackColor];
CGSize textShadowOffset = CGSizeMake(0.1, -0.1);
CGFloat textShadowBlurRadius = 5;
//// Abstracted Attributes
NSString* textContent = #"Update";
//// Back Rectangle Drawing
UIBezierPath* backRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(48, 53, 120, 23) cornerRadius: 4];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, buttonShadowOffset, buttonShadowBlurRadius, buttonShadow.CGColor);
CGContextBeginTransparencyLayer(context, NULL);
[backRectanglePath addClip];
CGContextDrawLinearGradient(context, gradient, CGPointMake(108, 53), CGPointMake(108, 76), 0);
CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);
//// Rounded Rectangle Drawing
UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(49, 54, 118, 21) cornerRadius: 3];
CGContextSaveGState(context);
[roundedRectanglePath addClip];
CGContextDrawLinearGradient(context, buttonGradient, CGPointMake(108, 54), CGPointMake(108, 75), 0);
CGContextRestoreGState(context);
//// Overlay Drawing
UIBezierPath* overlayPath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(48, 53, 120, 23) cornerRadius: 4];
CGContextSaveGState(context);
[overlayPath addClip];
CGContextDrawRadialGradient(context, overlayGradient,
CGPointMake(54.72, 38.09), 10,
CGPointMake(108, 11.46), 102.2,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
CGContextRestoreGState(context);
//// Text Drawing
CGRect textRect = CGRectMake(55, 54, 104, 21);
UIBezierPath* textPath = [UIBezierPath bezierPathWithRect: textRect];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, textShadowOffset, textShadowBlurRadius, textShadow.CGColor);
CGContextBeginTransparencyLayer(context, NULL);
[textPath addClip];
CGContextDrawLinearGradient(context, buttonGradient, CGPointMake(107, 54), CGPointMake(107, 75), 0);
CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);
[strokeColor setStroke];
textPath.lineWidth = 1;
[textPath stroke];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, textShadowOffset, textShadowBlurRadius, textShadow.CGColor);
[[UIColor whiteColor] setFill];
[textContent drawInRect: textRect withFont: [UIFont boldSystemFontOfSize: [UIFont systemFontSize]] lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentCenter];
CGContextRestoreGState(context);
//// Cleanup
CGGradientRelease(buttonGradient);
CGGradientRelease(overlayGradient);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
NSLog(#"drawRect exit");
}
#end
You do not need to implement initWithFrame: when using a Storyboard.
In fact, the storyboard will use initWithCoder: so it won't even be called.
I tested your code, and it works fine, however, you are not drawing in the top left corner, but somewhere in the middle of the view, so be sure to make the view large enough if you want to see your button.
Preferably draw in the top left corner.

Resources