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
516 views
in Technique[技术] by (71.8m points)

ios - How to change CAGradientLayer color points?

Right now I've got a GA Gradient layer where I've set the colors but I'd like to set the color point to (instead of top center, to top left) and the bottom to (instead of bottom center to bottom right) just to change things up a bit. Thoughts? Below is the code that I've got so far...I included core animation because I'm animation between colors.

- (id)init {
    self = [super init];

    UIView *gradientView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.w, self.h)];
    [self addSubview:gradientView];
    [self sendSubviewToBack:gradientView];

    topColor = [UIColor colorWithRed:0.012 green:0.012 blue:0.012 alpha:1];
    bottomColor = [UIColor colorWithRed:1.000 green:0.765 blue:0.235 alpha:1];

    gradient = [CAGradientLayer layer];
    gradient.frame = gradientView.frame;
    gradient.colors = [NSArray arrayWithObjects:(id)topColor.CGColor, (id)bottomColor.CGColor, nil];
    gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7], nil];
    [gradientView.layer addSublayer:gradient];

    [self performSelector:@selector(animateColors) withObject:self afterDelay:2.0];
    currentColorCount = 1;
    return self;
}

On the right (What I've got) on the left (what I'd like)

On the right (What I've got) on the left (what I'd like)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The startPoint and endPoint properties of a CAGradientLayer are defined in the “unit coordinate system”. In the unit coordinate system:

  • (0,0) corresponds to the smallest coordinates of the layer's bounds rectangle, which on iOS is its upper-left corner unless the layer has been transformed;
  • (1,1) corresponds to the largest coordinates of the layer's bounds rectangle, which on iOS is its lower-right corner unless the layer has been transformed.

Thus arranging your gradient the way you want should be this simple:

gradient.startPoint = CGPoint.zero
gradient.endPoint = CGPoint(x: 1, y: 1)

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

...