我想在 loc 550 处绘制一条渐变的水平线。
CGFloat colors[6] = {
138.0f / 255.0f, 1.0f,
162.0f / 255.0f, 1.0f,
206.0f / 255.0f, 1.0f};
CGFloat locations[3] = { 0.05f, 0.45f, 0.95f };
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, 3);
CGColorSpaceRelease(colorSpace);
CGPoint startPoint = CGPointMake(0, 0);
CGPoint endPoint = CGPointMake(0, 550);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextAddRect(context, CGRectMake(0, 550, self.view.bounds.size.width, 1));
CGContextClip(context);
CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
这段代码中没有绘制线条,Xcode 给出了这个错误:
CGContextAddRect: invalid context 0x0
最佳答案
您需要将此代码放置在 UIView
对象的 drawRect:
方法中,以确保当前上下文
存在。否则,您需要使用UIGraphicsPushContext
来获取当前上下文
。
来自documentation对于UIGraphicsGetCurrentContext()
:
The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current. If you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext function.
You should call this function from the main thread of your application only.
关于ios - 如何定义水平线的起点终点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941532/