Search code examples
ioscore-graphicslinear-gradients

CoreGraphics rectangle gradient


Can anyone help me in drawing one specific gradient with CoreGraphics? Just giving the clue would be enough. The example code whould get my deepest respect. I need this shape:

enter image description here

I tried the following code:

-(UIImage *)imageWithGradientBorder
{
    CGRect rect=CGRectMake(0, 0, self.size.width, self.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef ctx= CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, 8, rect.size.width, colorSpace, kCGImageAlphaNone);
    CGGradientRef glossGradient;
    size_t num_locations = 4;
    CGFloat locations[4] = { 0.0, 0.1, 0.9, 1.0 };
    CGFloat components[16] = { 0, 0, 0, 1, 1.0, 1.0, 1.0, 1, 1.0, 1.0, 1.0, 1, 0, 0, 0, 1};
    glossGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, num_locations);
    CGRect currentBounds = rect;

    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
    topCenter = CGPointMake( 0.0f, CGRectGetMidY(currentBounds));
    midCenter = CGPointMake(CGRectGetMaxX(currentBounds), CGRectGetMidY(currentBounds));

    CGContextDrawLinearGradient(ctx, glossGradient, topCenter, midCenter, 0);
    CGImageRef mask = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGImageRef maskedImageRef = CGImageCreateWithMask([self CGImage], mask);
    CGImageRelease(mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
    CGImageRelease(maskedImageRef);
    return maskedImage;
}

but it draws the gradient only from left side.


Solution

  • OK, I've produced one workaround.

    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextRef context = currentContext;
    CGContextSaveGState(currentContext);
    CGFloat colStep = 255 / borderWidth / 10;
    colStep = colStep / 255;
    for (int i = 0; i < floor(borderWidth * 10); i++) {
        CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:colStep*i alpha:1].CGColor);
        CGFloat delta = i / 10;
        CGRect rectToDraw = CGRectMake(delta,delta,rect.size.width - delta * 2,rect.size.height - delta * 2);
        CGContextFillRect(context, rectToDraw);
    }
    
    
    CGContextRestoreGState(currentContext);