钢琴白块之画轨道

来源:互联网 发布:手机淘宝联盟自己购买 编辑:程序博客网 时间:2024/05/01 20:13

在Swift中,可以在UIView上实现绘图的效果,有复杂的,也有简单的。在我的这个简陋的钢琴白块中,只实现了最最基础简单的绘图——直线绘图。

  • 第一,我们创建一个用于绘图的类
class drawRail:UIView {    override init(frame: CGRect) {        super.init(frame: frame)        //把背景色给去除        self.backgroundColor = UIColor.clearColor()    }}
  • 第二,在drawRail类中加入绘图方法
override func drawRect(rect: CGRect) {}

(这个绘图方法在每次调用drawRail类时都会启用)

  • 第三,在drawRect中添加绘制直线的代码
//获取设备的宽度和高度let weight = UIScreen.mainScreen().bounds.size.widthlet hight = UIScreen.mainScreen().bounds.size.heightlet context = UIGraphicsGetCurrentContext()CGContextSetLineWidth(context, 5)CGContextSetAllowsAntialiasing(context, true)//等分屏幕,画出3条竖线for i in 1...3 {    CGContextMoveToPoint(context, weight/4*CGFloat(i), 0)    CGContextAddLineToPoint(context, weight/4*CGFloat(i), hight)    CGContextStrokePath(context)}
  • 第四,在主控制视图中添加该轨道
//画布的范围是整个控制器的Viewlet drawView = drawRail(frame: self.view.framw)self.view.addSubview(drawView)

完成以上四步后,我们就可以在主控制器上看到三条竖线了。当然,我们可以绘制更多样式的图案,远远不止这几条硬生生的直线

0 0
原创粉丝点击