有幾種方法來實現你想要的。這裏有兩個例子: 請注意,這只是爲了向你展示一個例子,你應該添加參數/顏色/等等來獲得你想要的。希望這可以幫助。
1)直接繪製梯度圖。如果你希望額外的繪圖,也可以在視圖實現中調用[super drawRect:rect]。
- (void)drawRect:(CGRect)rect {
CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
if (CGSizeEqualToSize(self.centerOffset, CGSizeZero) == NO) {
center.x += self.centerOffset.width;
center.y += self.centerOffset.height;
}
CGContextRef currentContext = UIGraphicsGetCurrentContext();
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 0.0, 0.0, 0.0, 0.5, // Start color
0.0, 0.0, 0.0, 0.7 }; // End color
CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGGradientDrawingOptions options = kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation;
CGFloat endRadius = [UIApplication sharedApplication].keyWindow.bounds.size.height/2;
CGContextDrawRadialGradient(currentContext, gradient, center, 50.0f, center, endRadius, options);
CGGradientRelease(gradient);
CGColorSpaceRelease(rgbColorspace);
}
2)使用CAGradient層
UIColor *startEndColour = [UIColor redColor];
UIColor *middleColor = [UIColor blueColor];
NSArray *horizontalGradientColorsArray = [NSArray arrayWithObjects:(id)[startEndColour CGColor], (id)[middleColor CGColor],(id)[middleColor CGColor], (id)[startEndColour CGColor],nil];
UIView *horizontalGradient1View = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, self.bounds.size.width, 1.f)];
horizontalGradient1View.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
CAGradientLayer *horizontalGradient1 = [CAGradientLayer layer];
horizontalGradient1.frame = horizontalGradient1View.bounds;
horizontalGradient1.colors = horizontalGradientColorsArray;
horizontalGradient1.startPoint = CGPointMake(0, 0.5);
horizontalGradient1.endPoint = CGPointMake(1.0, 0.5);
[horizontalGradient1View.layer insertSublayer:horizontalGradient1 atIndex:0];
[self addSubview:horizontalGradient1View];
[horizontalGradient1View release];
謝謝您的回答。我意識到這些可能性,但基本上我試圖理解爲什麼代碼清單不工作(我需要爲CIImage提到的緩衝區) – Lukas