I am trying to draw a linear CGGradient at an angle. Since "CGContextDrawLinearGradientWithAngle ()" does not exist, I am trying to use CGContextDrawLinearGradient (CGContextRef, CGGradientRef, CGPoint startPoint, CGPoint endPoint, CGGradientDrawingOptions).
With that in mind, I need to convert the angle (degrees) to the start point and end point. I would like to imitate the NSGradient drawInBezierPath: angle. (The AppGit NSGradient, unfortunately, is not available to iOS developers.) Fortunately, the documentation tells us how to get the initial gradient :
- (CGPoint)startingPointForAngle:(CGFloat)angle rect:(CGRect)rect { CGPoint point = CGPointZero; if (angle < 90.0f) point = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)); else if (angle < 180.0f) point = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect)); else if (angle < 270.0f) point = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect)); else point = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)); return point; }
Unfortunately, the documentation does not indicate how to get the endpoint. (Using either the height or the width of the rectangle, since the distance is enough for certain angles.) Several sites out there tell us how we can find the end point. Unfortunately, the distance must be known before I can calculate the end point. However, the endpoint must be calculated in order to obtain the distance. There is clearly more, as NSGradient seems to have understood.
- (CGPoint)endingPointForAngle:(CGFloat)angle rect:(CGRect)rect startingPoint:(CGPoint)startingPoint { //http://www.zahniser.net/~russell/computer/index.php?title=Angle%20and%20Coordinates //(x + distance * cos(a), y + distance * sin(a)) CGFloat angleInRadians = (CGFloat)M_PI/180.0f * angle; CGFloat distance = ????????; CGPoint point = CGPointMake(startingPoint.x + distance * cosf(angleInRadians), startingPoint.y + distance * sinf(angleInRadians)); return point; } CGPoint startingGradientPoint = [self startingPointForAngle:self.fillGradientAngle rect:rect]; CGPoint endingGradientPoint = [self endingPointForAngle:self.fillGradientAngle rect:rect startingPoint:startingGradientPoint]; CGContextDrawLinearGradient(graphicsContext, self.fillGradient, startingGradientPoint, endingGradientPoint, 0);
Any ideas.