Drawing gradient over image in ios

后端 未结 5 658
天涯浪人
天涯浪人 2020-12-08 11:55

How to create gradient colour look like following image programatically.

\"enter

5条回答
  •  渐次进展
    2020-12-08 12:34

    -(void) drawGradientinBounds: (CGRect) currentBounds withColors:(NSArray*) colors andPercentages:(NSArray *)percentages andGradientDirectionIsVertical:(BOOL)isGradientDirectionVertical
    {
    
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
    
        CGGradientRef glossGradient;
        CGColorSpaceRef rgbColorspace;
    
        size_t num_locations = [percentages count];
        CGFloat locations[num_locations];
        for(int i=0;i=0;i--)
        {
            comps--;
            UIColor *c = [colors objectAtIndex:i];
            const CGFloat *cg = CGColorGetComponents([c CGColor]);
            components[comps] = cg[3];
            comps--;
            components[comps] = cg[2];
            comps--;
            components[comps] = cg[1];
            comps--;
            components[comps] = cg[0];
        }
    
        rgbColorspace = CGColorSpaceCreateDeviceRGB();
        glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    
        CGPoint topCenter;
        CGPoint endCenter;
    
        if(isGradientDirectionVertical)
        {
            topCenter = CGPointMake(CGRectGetMidX(currentBounds), currentBounds.origin.y);
            endCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetHeight(currentBounds)+currentBounds.origin.y);
    
        }
        else
        {
            topCenter = CGPointMake( currentBounds.origin.x,CGRectGetMidY(currentBounds));
            endCenter = CGPointMake(CGRectGetWidth(currentBounds)+currentBounds.origin.x,CGRectGetMidY(currentBounds));
        }
        CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, endCenter, 0);
    
        CGGradientRelease(glossGradient);
        CGColorSpaceRelease(rgbColorspace);
    }
    

    And the input to this method are bounds, colorArray:

    [NSArray arrayWithObjects:[UIColor blackColor], [UIColor whiteColor], nil]
    

    percentageArray:

    [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:1.0], nil] 
    

提交回复
热议问题