我打算做一個三角形,但你可以做多用重複:爲線性漸變的繪製代碼
//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);
}
你可以設置這個線性漸變函數可以處理兩個以上的位置/顏色,如果你願意的話。這是非常基本的,但如果你知道每個三角形的開始和停止顏色和位置,你應該能夠使用這個代碼(沒有數百個子圖層)完成你想要的(本地繪圖)。雖然圖層可能畫得更快,但我不知道。
我不知道爲什麼你幾次downvoted,所以這裏是一個+1,讓你再次。 – Michael
感謝邁克爾,感謝它;) – Andre