Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Four point gradient in iOS

I am planing to create a four point gradient, pictured below, by drawing two linear gradients via core graphics and masking between them with a third black and white linear gradient.

Is there a more efficient way to draw a four point gradient using core graphics, or other?

enter image description here

like image 965
Mr Ordinary Avatar asked Jul 14 '12 08:07

Mr Ordinary


People also ask

What is gradient iPhone?

Use gradients as color fills that blend smoothly from one color to another. Use a CSS gradient anywhere that you can use an image, such as for the background of an element, an element border, or a mask.

What is gradient layer in Swift?

You use a gradient layer to create a color gradient containing an arbitrary number of colors. By default, the colors are spread uniformly across the layer, but you can optionally specify locations for control over the color positions through the gradient.


2 Answers

Draw four circles:

Circles

Apply radial transparent gradient:

Gradient

Result:

Result

Notes:

  • The gray lines represent the bitmap size.
  • The diameter of the circles is twice the bitmap diameter.
  • Each circle is centered at one of the bitmap corner.
  • Effectively only the center part is drawn.
  • The remaining parts are outside the bitmap.
like image 174
Anne Avatar answered Oct 12 '22 00:10

Anne


You can save the mask gradient when you use a CGBlendMode. It's just harder to control the exact colors. But if that's not important for you, it could be a little more efficient in terms of lines of code and maybe also in terms of performance.

Here's an example with some random colors and CGBlendModeExclusion (CGBlendModeDifference gives you a similar effect)

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(ctx, kCGBlendModeExclusion);
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

    CGFloat col1[8] = {
        1.0, 0.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0
    };
    CGGradientRef grad1 = CGGradientCreateWithColorComponents (space, col1, NULL, 2);
    CGContextDrawLinearGradient(ctx, grad1, CGPointMake(0, 0), CGPointMake(0, 320), 0);


    CGFloat col2[8] = {
        1.0, 0.5, 0.0, 1.0,
        0.0, 1.0, 0.0, 1.0
    };
    CGGradientRef grad2 = CGGradientCreateWithColorComponents (space, col2, NULL, 2);
    CGContextDrawLinearGradient(ctx, grad2, CGPointMake(0, 0), CGPointMake(320, 0), 0);

    CGGradientRelease(grad1);
    CGGradientRelease(grad2);
    CGColorSpaceRelease(space);
}
like image 45
Dorian Roy Avatar answered Oct 12 '22 01:10

Dorian Roy