将渐变背景设置为ImageView,旋转

时间:2013-11-09 12:06:06

标签: ios objective-c uiimageview gradient

我想为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];

结果如下:

enter image description here

这是我的界面设置:

enter image description here

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

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

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

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

3 个答案:

答案 0 :(得分:3)

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

- (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;
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用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);