我将做一个三角形,但你可以使用重复做多个:
//Create the triangle Path and clip the drawing to it
CGContextSaveGState(context);
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.size.width * .4, self.bounds.size.height * 1/6.);
CGContextAddLineToPoint(context,self.bounds.size.width * .4, self.bounds.size.height * 3/6.);
CGContextAddLineToPoint(context,self.bounds.size.width * .2, self.bounds.size.height * 3/6.);
CGContextClosePath(context);
CGContextClip(context);
//Now call the linear gradient drawing function
[self drawLinearGradient:context withRect:self.bounds startColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:.3] endColor:[UIColor colorWithRed:.5 green:.5 blue:.5 alpha:.3] startFraction:.3 stopFraction:1];
//And now restore so that we can clip the next triangle
CGContextRestoreGState(context);
现在为线性渐变绘制代码:
- (void) drawLinearGradient: (CGContextRef) context withRect: (CGRect) rect startColor: (UIColor*) startColor endColor: (UIColor*) endColor startFraction:(float)start stopFraction:(float)stop
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { start, stop };
CGGradientRef myGradient;
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGColorRef startColorRef = [startColor CGColor];
CGColorRef endColorRef = [endColor CGColor];
const CGFloat *components = CGColorGetComponents(startColorRef);
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = components[3];
const CGFloat *components2 = CGColorGetComponents(endColorRef);
CGFloat red2 = components2[0];
CGFloat green2 = components2[1];
CGFloat blue2 = components2[2];
CGFloat alpha2 = components2[3];
CGFloat colors[] =
{
red, green, blue, alpha,
red2, green2, blue2, alpha2
};
myGradient = CGGradientCreateWithColorComponents(rgb, colors, locations, 2);
CGColorSpaceRelease(rgb);
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, myGradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(myGradient);
CGColorSpaceRelease(colorSpace);
}
如果你愿意,你可以设置这个线性渐变函数来处理两个以上的位置/颜色。这是非常基本的,但是如果您知道每个三角形的开始和停止颜色以及位置,您应该能够使用此代码(无需数百个子层)完成您想要的(本机绘图)。虽然图层可能绘制得更快,但我不知道。