Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

objective c - iPhone iOS how to add linear gradient to a UIButton under the button's text or image?

I'm working on creating fancy looking UIbuttons by adding linear gradient to the button. However I'm not sure at which index I need to add the gradient. The code that I have currently places the gradient over the image/text.

How can I insert a sublayer to a UIButton under the text/image sublayer? It is important for me to keep the text and the image of a button visible!

+(void)addLinearGradientToView:(UIView*)view TopColor:(UIColor*)topColor BottomColor:(UIColor*)bottomColor
{
    for(CALayer* layer in view.layer.sublayers)
    {
        if ([layer isKindOfClass:[CAGradientLayer class]])
        {
            [layer removeFromSuperlayer];
        }
    }
    CAGradientLayer* gradientLayer = [CAGradientLayer layer];

    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5,1);
    gradientLayer.frame = view.bounds;
    gradientLayer.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
    //    [view.layer addSublayer:gradientLayer];
    if(view.layer.sublayers.count>0)
    {
        [view.layer insertSublayer:gradientLayer atIndex:view.layer.sublayers.count-2];
    }else {
        [view.layer addSublayer:gradientLayer];
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add it to the layer of your custom button:

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = customButton.layer.bounds;

gradientLayer.colors = [NSArray arrayWithObjects:
                        (id)[UIColor colorWithWhite:1.0f alpha:0.1f].CGColor,
                        (id)[UIColor colorWithWhite:0.4f alpha:0.5f].CGColor,
                        nil];

gradientLayer.locations = [NSArray arrayWithObjects:
                           [NSNumber numberWithFloat:0.0f],
                           [NSNumber numberWithFloat:1.0f],
                           nil];

gradientLayer.cornerRadius = customButton.layer.cornerRadius;
[customButton.layer addSublayer:gradientLayer];

where customButton is your custom UIButton.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...