我是Xcode和iOS开发的新手。我试图在图层中绘制渐变,以便在我的视图中重复绘制此图层。这个渐变形成了视图的背景,我对这个渐变做了一些绘制。但是,当我在图层中绘制渐变,然后在视图的上下文中绘制渐变时,它不绘制渐变。我试过调试代码,但一切似乎都很好。粘贴下面的相关代码: 我在开始时创建了gradientLayer。无法将渐变绘制成图层CGLayerRef
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect myRect = self.bounds;
CGGradientRef myGradient;
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] =
{
204.0/255.0, 224.0/255.0, 244.0/255.0, 1.00,
100/255.0, 200/255.0, 50/255.0, 1.00,
0, 0, 0, 1.00,
};
myGradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
CGColorSpaceRelease(rgb);
CGContextRef layerContext = CGLayerGetContext(gradientLayer);
CGPoint start, end;
CGRect clip = CGContextGetClipBoundingBox(layerContext);
start = getStartPoint(clip);
end = getEndPoint(clip);
CGContextDrawLinearGradient(layerContext, myGradient, start, end, 0);
//CGContextSetRGBFillColor (layerContext, red/255.0, green/255.0, blue/255.0, 1);
//CGContextFillRect (layerContext, clip);
当我的类被实例化时,我调用了这个函数。然后在我的drawRect方法中重复绘制这个图层。
CGRect rect = self.bounds;
CGContextSaveGState(context);
CGContextDrawLayerInRect(context, rect, gradientLayer);
CGContextSaveGState(context);
我可以直接得出同样的梯度在drawRect中,但我无法这样做拉丝成层,然后在drawRect中时(试图优化图)。