【问题标题】:Set a gradient Background to ImageView, rotation为 ImageView 设置渐变背景,旋转
【发布时间】:2023-07-09 09:01:01
【问题描述】:

我想为我的 ImageView 设置一个渐变背景。我在 Stack Overflow 上找到了解决方案。但这并不能真正满足我的需求。

我希望渐变从左到右。使用我发现的代码,我只能从上到下填充它。

我用这段代码创建了渐变层:

+ (CAGradientLayer *)colorGradientWithColor:(UIColor *)color
{
    UIColor *colorOne = color;
    UIColor *colorTwo = [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0f];

    NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];

    NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
    NSNumber *stopTwo = [NSNumber numberWithFloat:0.9];

    NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, nil];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = colors;
    gradientLayer.locations = locations;

    return gradientLayer;
}

然后我将图层添加到我的UIImageView

CAGradientLayer *gradientLayer = [BackgroundGradient colorGradientWithColor:difficultyColor];
gradientLayer.frame = myImageView.bounds;
[myImageView.layer insertSublayer:gradientLayer atIndex:0];

结果如下:

这里是我的界面设置:

如您所见,有两个UIImageViews。我想在渐变视图中旋转图层,所以它是从左到右而不是现在的样子。

通过以下代码片段,我可以旋转整个ImageView。这只能解决我的问题,但我不希望这样,因为它会破坏我的界面..

myImageView.transform = CGAffineTransformMakeRotation(M_PI*1.5f);

所以基本上我正在寻找一种从左到右而不是从上到下进行渐变的解决方案。
你们有什么想法吗?我是 XCode 的新手,我将不胜感激!

【问题讨论】:

    标签: ios objective-c uiimageview gradient


    【解决方案1】:

    这是我从下面的代码得到的结果。我想这就是你想要实现的目标

    - (CAGradientLayer *)colorGradientWithColor:(UIColor *)color
    {
        UIColor *colorOne = color;
        UIColor *colorTwo = [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0f];
    
        NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];
    
        NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
        NSNumber *stopTwo = [NSNumber numberWithFloat:0.9];
    
        NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, nil];
    
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        [gradientLayer setStartPoint:CGPointMake(0.0, 0.5)];//add these lines
        [gradientLayer setEndPoint:CGPointMake(1.0, 0.5)];
        gradientLayer.colors = colors;
        gradientLayer.locations = locations;
    
        return gradientLayer;
    }
    

    【讨论】:

      【解决方案2】:

      尝试在将图层添加到 imageview 之前旋转图层,使用变换。

      【讨论】:

        【解决方案3】:

        使用gradient 层的起点和终点:

        BOOL horizontal = YES;
        //(YES for left to right or NO for top to bottom)
        
        gradientLayer.startPoint = horizontal ? CGPointMake(0, 0.5) : CGPointMake(0.5, 0);
        
        gradientLayer.endPoint   = horizontal ? CGPointMake(1, 0.5) : CGPointMake(0.5, 1);
        

        【讨论】: