UISegmentedControl tintColor渐变

时间:2016-07-06 15:51:20

标签: ios objective-c gradient uisegmentedcontrol

我正在尝试将UISegmentedControl的foreground / tintColor设置为水平渐变。我希望渐变在控件上延伸,并在单击每个片段时进行适当调整。见下图:

Desired UISegmentedControl gradient

我已经尝试使用找到的堆栈溢出解决方案here设置tintColor,但是当我将其更改为水平时,使用colorWithPattern似乎不起作用:

enter image description here

以下是我现在正在使用的内容:

UIView* test2 = [[UIView alloc] initWithFrame:CGRectMake(10, 60, 200, 25)];
test2.backgroundColor = [self gradientFromColor:[UIColor redColor] toColor:[UIColor greenColor] withWidth:test2.frame.size.width];
[self.view addSubview:test2];

UISegmentedControl *test = [[UISegmentedControl alloc] initWithItems:@[@"one", @"two"]];
test.frame = CGRectMake(10, 100, 200, 25);
test.tintColor = [self gradientFromColor:[UIColor redColor] toColor:[UIColor greenColor] withWidth:test.frame.size.width];
[self.view addSubview:test];

...

- (UIColor*) gradientFromColor:(UIColor*)c1 toColor:(UIColor*)c2 withWidth:(int)width{
    CGSize size = CGSizeMake(width, 1);

    UIGraphicsBeginImageContextWithOptions(size, NO, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

    NSArray* colors = [NSArray arrayWithObjects:(id)c1.CGColor, (id)c2.CGColor, nil];
    CGGradientRef gradient = CGGradientCreateWithColors(colorspace, (CFArrayRef)colors, NULL);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(width, 0), 0);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorspace);
    UIGraphicsEndImageContext();

    return [UIColor colorWithPatternImage:image];
}

我想我需要做一些掩盖工作,但我一直无法让它工作。

0 个答案:

没有答案