draw_rect,按需绘制

来源:互联网 发布:无线键盘鼠标 知乎 编辑:程序博客网 时间:2024/04/27 14:19

改变控件的样子

添加了一个button,默认的样子太单一,希望换种样式,可以给它指定一个image。
不过这里还有另外一种很简单的方法,就是自定义一个class,继承自UIButton,然后覆盖默认的draw_rect,就可以在里面改变样式了。



Core Graphics是专门用来进行图形绘制的。apple封装了一个UIKit,简化了core graphics的操作。

如何使用UIkit绘制呢?这里有一段简单的代码, 其中UIBezierPath是用来定义路径的。

var path = UIBezierPath(ovalInRect: rect)//以rect为外切矩形,绘制椭圆fillColor.setFill()// 填充色path.fill() //填充

让自定义的显示在stroyboard中起来

draw_rect中虽然添加了一些新的绘制,但是不能从storyboard中看到,每次都要build才能知道自己的绘制结果,这样真是麻烦。

不过apple给我们提供了下面的方法,让我们的draw_rect能够从storyboard直接看到,太给力了

@IBDesignable – Interactive Drawing

  • just before the class declaration

@IBInspectable – Custom Storyboard Properties

  • @IBInspectable is an attribute you can add to a property that makes it readable by Interface Builder.

CoreGraphic

在前面的代码中,我们使用了UIBezierPath绘制路径,UIBezierPath是UIKit封装的方法,调用的是更底层的Core Graphics,它们之间的关系可以在前面的图片中看出。

Core Graphics函数具有这些特点:

  • 以CG开头
  • 都是C函数

绘制一个如下所示的图形




代码如下:

override func drawRect(rect: CGRect) {    let path = UIBezierPath(roundedRect: rect,        byRoundingCorners: UIRectCorner.AllCorners,        cornerRadii: CGSizeMake(8.0, 8.0))    path.addClip() //圆角    let context = UIGraphicsGetCurrentContext()//获取context    let colors = [startColor.CGColor, endColor.CGColor]    let colorSpace = CGColorSpaceCreateDeviceRGB()    let colorLocation: [CGFloat] = [0.0, 1.0]    let gradient = CGGradientCreateWithColors(colorSpace,        colors,        colorLocation)    let startPoint = CGPoint.zero    let endPoint = CGPoint(x: 0, y: bounds.height)    CGContextDrawLinearGradient(context,        gradient,        startPoint,        endPoint,        CGGradientDrawingOptions.DrawsAfterEndLocation)}
0 0