How to fill a UIBezierPath with a gradient? - ios

I've drawn a graph using a UIBezierPath. I can fill the area under the graph with a solid color but I want to fill the area under the graph with a gradient rather than with a solid color. But I'm not sure how to make the gradient apply only to the graph and not to the whole view, I've read a few questions but not found anything applicable.
This is the main graph drawing code:
// Draw the graph
UIBezierPath *barGraph = [UIBezierPath bezierPath];
barGraph.lineWidth = 1.0f;
[blueColor setStroke];
TCDataPoint *dataPoint = self.testData[0];
CGFloat x = [self convertTimeToXPoint:dataPoint.time];
CGFloat y = [self convertDataToYPoint:dataPoint.dataUsage];
CGPoint plotPoint = CGPointMake(x,y);
[barGraph moveToPoint:plotPoint];
for (int ii = 1; ii < [self.testData count]; ++ii)
{
dataPoint = self.testData[ii];
x = [self convertTimeToXPoint:dataPoint.time];
y = [self convertDataToYPoint:dataPoint.dataUsage];
plotPoint = CGPointMake(x, y);
[barGraph addLineToPoint:plotPoint];
}
[barGraph stroke];
I've been attempting to fill the graph by experimenting with code like the following, but to be honest am not %100 sure what I'm doing despite going through various tutorials and documentation:
[barGraph closePath];
CGFloat colors [] = {
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 1.0, 1.0
};
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace);
CGPoint startPoint = CGPointMake(CGRectGetMidX(self.bounds), self.topY);
CGPoint endPoint = CGPointMake(CGRectGetMidX(self.bounds), self.bottomY);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);

The easiest approach is to use the original graph bezier path to help you construct a mask and impose this mask on a gradient layer. Now impose the graph layer on top of the gradient layer.
So, for example, make a CAShapeLayer, close the graph bezier path, set its path as the shape layer's path, and fill it black. Now you have a mask that is the shape of the area under the graph. Now make a CAGradientLayer and make the CAShapeLayer its mask. In front of that, place the actual graph.
So for example (EDITED):
Here's the code I used to create that drawing (my bezier path is very simple, just four points joined by three lines, but you can see clearly that the area under it is a gradient):
CAShapeLayer* shape = [[CAShapeLayer alloc] init];
shape.frame = self.graph.bounds;
CGFloat h = shape.frame.size.height;
CGFloat w = shape.frame.size.width;
NSArray* points = #[
[NSValue valueWithCGPoint:CGPointMake(0,h-50)],
[NSValue valueWithCGPoint:CGPointMake(70,h-100)],
[NSValue valueWithCGPoint:CGPointMake(140,h-75)],
[NSValue valueWithCGPoint:CGPointMake(w,h-150)],
];
UIBezierPath* p = [UIBezierPath new];
[p moveToPoint:[points[0] CGPointValue]];
for (NSInteger i = 1; i < points.count; i++)
[p addLineToPoint:[points[i] CGPointValue]];
shape.path = p.CGPath;
shape.strokeColor = [UIColor blackColor].CGColor;
shape.lineWidth = 2;
shape.fillColor = nil;
CAGradientLayer* grad = [[CAGradientLayer alloc] init];
grad.frame = self.graph.bounds;
grad.colors = #[(id)[UIColor blueColor].CGColor,
(id)[UIColor yellowColor].CGColor];
CAShapeLayer* mask = [[CAShapeLayer alloc] init];
mask.frame = self.graph.bounds;
[p addLineToPoint:CGPointMake(w,h)];
[p addLineToPoint:CGPointMake(0,h)];
[p closePath];
mask.path = p.CGPath;
mask.fillColor = [UIColor blackColor].CGColor;
grad.mask = mask;
[self.graph.layer addSublayer:grad];
[self.graph.layer addSublayer:shape];

Related

How to fill a bezier path with control points with gradient color

I need to fill my bezier path with a gradient color. But the effect is not what I expected, I know this is caused by the drawing direction.
How can I achieve the effect of the second picture?
my bezierpath code
CGFloat deltaX = lineChartPoint.x - previousLineChartPoint.x;
CGFloat controlPointX = previousLineChartPoint.x + (deltaX / 2);
CGPoint controlPoint1 = CGPointMake(controlPointX, previousLineChartPoint.y);
CGPoint controlPoint2 = CGPointMake(controlPointX, lineChartPoint.y);
[bezierPath addCurveToPoint:CGPointMake(lineChartPoint.x, lineChartPoint.y) controlPoint1:controlPoint1 controlPoint2:controlPoint2];
my gradientLayer code
self.gradientLayer = [CAGradientLayer layer];
self.gradientLayer.frame = CGRectMake(kVPadding, 0, CGRectGetWidth(self.bounds) - 2 * kVPadding, CGRectGetHeight(self.bounds));
self.gradientLayer.colors = #[(__bridge id)[UIColor colorWithHex:0x8362FC alpha:0.9].CGColor,(__bridge id)[UIColor colorWithHex:0x517DF7 alpha:0.1].CGColor];
self.gradientLayer.locations=#[#0.0,#1.0];
self.gradientLayer.startPoint = CGPointMake(0.0,0.0);
self.gradientLayer.endPoint = CGPointMake(0.0,1);
[self.layer addSublayer:self.gradientLayer];
self.gradientShapeLayer = [[CAShapeLayer alloc] init];
self.gradientLayer.mask = self.gradientShapeLayer;
self.gradientShapeLayer.path = bezierPath.CGPath;
#Dragonthoughts

How to set gradient color with angle

I want to set gradient on my button, i have to set simple linear gradient(without angle) with two color, but i don't know how to set angle value on gradient
Angle:- 61
below image define psd gradient overlay effect
Thanks in advance
Try it, maybe it will help
- (CAGradientLayer *)gradientLayerWithColors:(NSArray *)colors angle:(CGFloat)angle {
CAGradientLayer *layer = [CAGradientLayer layer];
layer.colors = colors;
CGFloat x = angle / 360.f;
CGFloat a = pow(sin((2*M_PI*((x+0.75)/2))),2);
CGFloat b = pow(sin((2*M_PI*((x+0.0)/2))),2);
CGFloat c = pow(sin((2*M_PI*((x+0.25)/2))),2);
CGFloat d = pow(sin((2*M_PI*((x+0.5)/2))),2);
layer.startPoint = CGPointMake(a, b);
layer.endPoint = CGPointMake(c, d);
return layer;
}
CAGradientLayer *gradientMask = [CAGradientLayer layer];
gradientMask.frame = CGRectMake(0, 0, myView.bounds.size.width, myView.bounds.size.height);
gradientMask.colors = #[(id)[UIColor redColor].CGColor,
(id)[UIColor greenColor].CGColor];
gradientMask.locations = #[#0.0, #0.10, #0.60, #1.0];
[myView.layer insertSublayer:gradientMask atIndex:0];
adjust location value and frame size accordingly.
This is a slightly modified code generated by PaintCode that solves just this problem:
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: self.view.bounds];
UIBezierPath* rectangleRotatedPath = [rectanglePath copy];
CGAffineTransform transform = CGAffineTransformMakeRotation(yourAngleInRadians);
[rectangleRotatedPath applyTransform: transform];
CGRect rectangleBounds = CGPathGetPathBoundingBox(rectangleRotatedPath.CGPath);
transform = CGAffineTransformInvert(transform);
CGPoint startPoint = CGPointApplyAffineTransform(CGPointMake(CGRectGetMinX(rectangleBounds), CGRectGetMidY(rectangleBounds)), transform);
CGPoint endPoint = CGPointApplyAffineTransform(CGPointMake(CGRectGetMaxX(rectangleBounds), CGRectGetMidY(rectangleBounds)), transform);
The code takes your initial rectangle (black rectangle) and angle (shown as black line), rotates the rectangle (you'll get blue rectangle), then finds bounding box of the rotated rectangle (red rectangle). Takes endpoints on the bounds (red dots) and transforms (rotates) them back using invert transform (blue dots).
Other solution might be finding intersection of your rectangle and a line defined by the angle.

Implement drawing gradient arc with CAShapeLayer

Referring to the accepted answer found here I'm trying to implement this and running into an issue with the path of the CAShapeLayerThe code I have is as follows:
-(void)drawGradientArc{
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
CAShapeLayer *circleLayer = [CAShapeLayer new];
circleLayer.lineWidth = 25;
circleLayer.fillColor = [UIColor clearColor].CGColor;
circleLayer.strokeColor = [UIColor redColor].CGColor;
CGFloat radius = 150;
[bezierPath addArcWithCenter:self.view.center radius:radius startAngle:0 endAngle:M_PI clockwise:YES];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.startPoint = CGPointMake(0,0);
gradientLayer.endPoint = CGPointMake(1,0);
NSMutableArray *colors = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[colors addObject:(id)[[UIColor colorWithHue:(0.1 * i) saturation:1 brightness:.8 alpha:1] CGColor]];
}
gradientLayer.colors = colors;
[gradientLayer setMask:circleLayer];
circleLayer.path = bezierPath.CGPath;
[self.view.layer addSublayer:circleLayer];
}
This will draw the half circle arc correctly but the path for the gradients is not being set correctly and I was unable to piece together how exactly to configure the code to get this to work using a gradient. There is a CGPathCreateCopyByStrokingPath that I think I may also need to call to set the path properly for the gradient but was not quite sure how. Any help on how to structure the code to get this working would be appreciated. I've also included an image of the gradient that I'm trying to reproduce. a CAShapeLayer and CAGradientLayerapproach would be ideal.
Problem 1: Your layers have no frames. Add this:
gradientLayer.frame = self.view.layer.bounds;
circleLayer.frame = gradientLayer.bounds;
Problem 2: You are adding the wrong layer to your view's layer. Where you have:
[self.view.layer addSublayer:circleLayer];
say this instead:
[self.view.layer addSublayer:gradientLayer];
Result:

UIBezierPath with multiples arcs

Hiiii
I'm trying to draw in a view an arc with dynamic width.
I have built an ARRAY with several UIBezierPath with arcs then I draw one after the other. this is the code:
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGFloat radious;
if (self.bounds.size.width < self.bounds.size.height) {
radious = self.bounds.size.width / 2;
}
else{
radious = self.bounds.size.height / 2;
}
float oneGradeInRadians = (float)(2 * M_PI) / 360.f;
float radiandToDraw = (float)self.finalAngleRadians - self.initialAngleRadians;
float splitMeasure = oneGradeInRadians;
int numberOfArcs = radiandToDraw / splitMeasure;
NSMutableArray *arrayOfBeziersPaths = [NSMutableArray arrayWithCapacity:numberOfArcs];
for (int i = 0; i < numberOfArcs; i++) {
float startAngle = self.initialAngleRadians + (i * splitMeasure);
float endAngle = self.initialAngleRadians +((i + 1) * splitMeasure);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height/2) radius:radious - self.widthLine.floatValue startAngle:startAngle endAngle:endAngle clockwise:YES];
bezierPath.lineWidth = self.widthLine.floatValue + i/20;
float hue = (float)(i / 3.f);
UIColor *color = [UIColor colorWithHue:hue/360.0 saturation:1 brightness:1 alpha:1];
[color setStroke];
[arrayOfBeziersPaths addObject:bezierPath];
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineJoin(context, kCGLineJoinMiter);
//We saved the context
CGContextSaveGState(context);
for (int i = 0; i < numberOfArcs; i++) {
[(UIBezierPath *)[arrayOfBeziersPaths objectAtIndex:i] stroke];
[(UIBezierPath *)[arrayOfBeziersPaths objectAtIndex:i] fill];
}
//Restore the contex
CGContextRestoreGState(context);
}
In this way I get the right shape but, also I get an annoying lines between the arcs:
I think the problem may be a property to change between arcs, but I'm totally lost, or maybe there is another better way to build this.
I tried creating several UIBezierPath paths and I added them to an unique UIBezierPath, then I stoke and fill that path. I didn't get the annoying lines, but the problem is I can not modify the line width, so I can not get the same effect.
Any idea? thanks
dont create many such paths. just create two arcs (inner circle, exterior circle) and two straight lines joining the ends. then fill the path.
Add below code in a viewDidLoad of an empty viewController and check.
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat k =0.5522847498;
UIBezierPath *path =[UIBezierPath bezierPath];
CGFloat radius=130;
[path addArcWithCenter:CGPointMake(0, 0) radius:radius startAngle:M_PI_2 endAngle:M_PI clockwise:NO];
CGFloat start=10;
CGFloat increment=5;
[path addLineToPoint:CGPointMake(-radius-start, 0)];
[path addCurveToPoint:CGPointMake(0, -radius-start-increment) controlPoint1:CGPointMake(-radius-start, -(radius +start)*k) controlPoint2:CGPointMake(-(radius+start)*k, -radius-start-increment)];
[path addCurveToPoint:CGPointMake(radius+start+2*increment, 0) controlPoint1:CGPointMake((radius+start+increment)*k, -radius-start-increment) controlPoint2:CGPointMake(radius+start+2*increment, (-radius-start-increment)*k)];
[path addCurveToPoint:CGPointMake(0, radius+start+3*increment) controlPoint1:CGPointMake(radius+start+2*increment, (radius+start+2*increment)*k) controlPoint2:CGPointMake((radius+start+2*increment)*k,radius+start+3*increment)];
[path addLineToPoint:CGPointMake(0,radius)];
CAShapeLayer *layer =[CAShapeLayer layer];
[layer setFrame:CGRectMake(150, 200, 300, 300)];
[layer setFillColor:[UIColor greenColor].CGColor];
[layer setStrokeColor:[UIColor blackColor].CGColor];
[layer setPath:path.CGPath];
[self.view.layer addSublayer:layer];
}
It produced result like,
The problem here is that you’ve chosen a crazy approach to drawing the shape you’re after. If you take a look at it, you’ll see that it’s actually a filled region bounded on the outside by a circular arc, and on the inner edge by a spiral.
What you should do, therefore, is create a single NSBezierPath, add the outer circular arc to it, then add a line to the start of your spiral, append a spiral (you’ll want to approximate it with Bézier segments) and finally call -closePath. After that, you can -fill the path and you’ll get a good looking result rather than the mess you have above.

Invert a radial gradient mask in core graphics

I am able to mask a picture with black/white radial gradient in iOS using core graphics. But I am getting result just the opposite I want. I want the picture to be transparent from the region where gradient is applied and shall display the remaining part of the picture. That means a "![hole][1]" in the picture. But here the hole will be created by a gradient mask.
Can anyone please suggest me some way or any hint to invert the radial gradient mask, just like we do in photoshop.
Instead of using mask, I think the best way is to insert the layer. That's what I did for my IOS app.
- (void) addSublayer {
CGPoint center = CGPointMake(self.addButton.frame.origin.x, self.addButton.frame.origin.y);
UIBezierPath* clip = [UIBezierPath bezierPathWithArcCenter:center
radius:CGRectGetMaxX(self.addUnavailabilitySubView.frame) - self.addButton.center.x
startAngle:-1.57
endAngle:1.57
clockwise:YES];
[clip addLineToPoint:center];
[clip closePath];
CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
[shapeLayer setMasksToBounds:YES];
shapeLayer.frame = self.view.layer.bounds;
shapeLayer.path = clip.CGPath;
//This gradient layer can be a customised one
CALayer *gradientLayer = [CALayer layer];
gradientLayer.frame = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width);
[self.view.layer insertSublayer:gradientLayer atIndex:0];
}
I can also share my radial gradient layer here :)
-(void)drawInContext:(CGContextRef)ctx {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 }; // End color
CGFloat components[8] = {0.f, 0.f, 0.f, 0.3f, 0.f, 0.f, 0.f, 0.8f};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, num_locations);
CGFloat myStartRadius, myEndRadius;
CGPoint radialCenter = CGPointMake(100, 100)
myStartRadius = 20;
myEndRadius = 300;
CGContextDrawRadialGradient (ctx, gradient, radialCenter,
myStartRadius, radialCenter, myEndRadius,
kCGGradientDrawsAfterEndLocation);
}

Resources