ios - 如何定义水平线的起点终点

标签 ios

我想在 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/

相关文章:

iOS - 获取字母的 "real"高度

ios - 在 CABasicAnimation 中使用 #keyPath 时,类型 'CGPoint' 没有成员 'x'

objective-c - 在 iOS 上,使用 Instruments,我们是否必须编译程序并运行它并停止它,然后在 Instrument 中按 Record 以查看使用的内存?

ios - 我应该删除生产的firebase调试吗

ios - 无法将接口(interface)类型为 'NSString' 的对象按值传递给可变参数函数;格式字符串的预期类型为 'id'

ios - 如何管理构建 iPhone 应用程序的精简版与付费版?

ios - iOS 中轮询网络服务任务完成情况的最佳实践

ios - 多个不同尺寸的自定义单元

php - 如何快速保护身份验证

iOS 照片扩展 finishContentEditing WithCompletionHandler : Unable to Save Changes