带有 GradientLayer 的 UIButton 使图像模糊并使渐变变暗

UIButton with GradientLayer obscures image and darkens gradient(带有 GradientLayer 的 UIButton 使图像模糊并使渐变变暗)

本文介绍了带有 GradientLayer 的 UIButton 使图像模糊并使渐变变暗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个 UIButton,我希望将渐变作为图像下方的背景(具有透明背景的符号),但我面临两个不同的问题.

I have an UIButton here where I'd like to have a gradient as the background below the image (symbol with transparent background), but I'm facing two different problems.

无论我如何尝试添加,CAGradientLayer 的第一个似乎都覆盖在图像之上,完全遮蔽了图像.

First of the CAGradientLayer seems to overlay on top of the image no matter how I try to add it, obscuring the image completely.

其次,渐变本身似乎变暗了很多,就像按钮被禁用一样,但事实并非如此.

Secondly the gradient itself seems to be darkened a lot, like the button was disabled, which it isn't.

这是我的代码:

self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 35, 28, 28)];
[backButton addTarget:self
               action:@selector(goBack)
     forControlEvents:UIControlEventTouchUpInside];
[backButton setBackgroundColor:[UIColor clearColor]];
CAGradientLayer *buttonGradient = [CAGradientLayer layer];
buttonGradient.frame = backButton.bounds;
buttonGradient.colors = [NSArray arrayWithObjects:
                         (id)[[UIColor colorWithRed:.0
                                              green:.166
                                               blue:.255
                                              alpha:1] CGColor], 
                         (id)[[UIColor colorWithRed:.0
                                              green:.113
                                               blue:.255
                                              alpha:1] CGColor], 
                         nil];
[buttonGradient setCornerRadius:backButton.frame.size.width / 2];
[backButton.layer insertSublayer:buttonGradient
                         atIndex:0];
[backButton setImage:[UIImage imageNamed:@"backarrow.png"]
            forState:UIControlStateNormal];
[backButton setEnabled:NO];
[topbarView addSubview:backButton];

推荐答案

所以我设法通过在添加渐变后执行 [button bringSubviewToFront:button.imageView] 来解决这个问题.似乎无论我做什么,新层都会添加到 imageView 之上,所以我需要在之后将它推到前面.

So I managed to get around this by doing a [button bringSubviewToFront:button.imageView] after adding the gradient. Seems that no matter what I do the new layer will add on top of the imageView, so I need to push that to the front afterwards.

目标-C:

[button bringSubviewToFront:button.imageView] 

Swift 4.1:

button.bringSubview(toFront:button.imageView!)

这篇关于带有 GradientLayer 的 UIButton 使图像模糊并使渐变变暗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:带有 GradientLayer 的 UIButton 使图像模糊并使渐变变暗

基础教程推荐