美文网首页iOSiOS-swift
iOS开发 - 画线 方便自定义细线

iOS开发 - 画线 方便自定义细线

作者: 小黑Swift | 来源:发表于2016-12-25 08:54 被阅读263次
    某些时候我们需要一些细节调整,可以自己自定义线,下面是画直线的例子。同时提供 View 转 Image 方法,方便某些时候直接当图像使用。
    /// 自定义线视图
    class LineView: UIView {
        
        /// 快速创建 默认全屏  height 高度
        static func creatLineView(height height:CGFloat) -> LineView {
            let lineView = LineView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height))
            lineView.backgroundColor = UIColor.clearColor()
            return lineView
        }
        
        /// 画直线
        override func drawRect(rect: CGRect) {
            
            let context = UIGraphicsGetCurrentContext()
            CGContextSetAllowsAntialiasing(context, true)
            CGContextSetLineWidth(context, self.frame.height)
            
            CGContextSetRGBStrokeColor(context, 136/255, 136/255, 136/255, 1)// 颜色
            CGContextBeginPath(context)
            
            CGContextMoveToPoint(context, 0, 0);  //起点坐标
            CGContextAddLineToPoint(context, self.frame.size.width, 0) //终点坐标
            
            CGContextStrokePath(context)
        }
    }
    
    extension LineView {
        /// View -> UIImage
        func convertViewToImage() -> UIImage {
            let size = self.bounds.size
            //UIGraphicsBeginImageContext(size)
            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
            self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }

    相关文章

      网友评论

        本文标题:iOS开发 - 画线 方便自定义细线

        本文链接:https://www.haomeiwen.com/subject/yqbrvttx.html