swift开发笔记10 - 通过drawRect自定义控件外观

来源:互联网 发布:男人月薪4500 知乎 编辑:程序博客网 时间:2024/04/19 09:32

需要实现按钮如下:


大致思路:拖一个普通按钮到storyboard,然后新建一个类继承UIButton,重写其drawRect方法,最后把按钮的custom class设置为该类。

按钮与其自定义类DateButton:


1、用代码设置按钮边框线,写在viewcontroller中:


        Datebutt.layer.borderWidth=1        Datebutt.layer.borderColor=UIColor.colorWithHexString("#e83636").CGColor        Datebutt.layer.cornerRadius=5.0

先把按钮弄成这样:


然后把按钮的下半部分填充颜色,并重绘文本

其中UIColor.colorWithHexString()是自己写的扩展,详见前面的笔记

2、增加DateButton类,在drawRect中使用Quartz的CGContextAddArcToPoint来绘制圆角曲线,用NSString.sizeWithAttributes来计算文本宽度,实现按钮文字居中

import UIKitclass DateButton: UIButton {        override func drawRect(rect: CGRect) {        let buttonRect=self.layer.frame        let contextRef = UIGraphicsGetCurrentContext();        CGContextSetFillColorWithColor( contextRef, UIColor.colorWithHexString("#e83636").CGColor);        //绘制矩形        //CGContextMoveToPoint(contextRef, 0, buttonRect.size.height/2);//左上        //CGContextAddLineToPoint(contextRef, buttonRect.size.width, buttonRect.size.height/2);//右上        //CGContextAddLineToPoint(contextRef, buttonRect.size.width, buttonRect.size.height);//右下        // CGContextAddLineToPoint(contextRef, 0, buttonRect.size.height);//左下        //绘制下圆角矩形        CGContextMoveToPoint(contextRef, 0, buttonRect.size.height/2)//左上        CGContextAddLineToPoint(contextRef, buttonRect.size.width, buttonRect.size.height/2)//右上        //绘制从路径的当前点(作为开始点)到结束点(x、y)的贝塞尔曲线,其中,2,3参数定义第一个控制点的坐标;4,5定义终点坐标,最后一个是半径        CGContextAddArcToPoint(contextRef, buttonRect.size.width, buttonRect.size.height, buttonRect.size.width-5, buttonRect.size.height,5)//右下圆角        CGContextAddLineToPoint(contextRef, 5, buttonRect.size.height)//右中        CGContextAddArcToPoint(contextRef, 0, buttonRect.size.height,  0, buttonRect.size.height-5,5)//左下圆角        CGContextClosePath(contextRef)        CGContextDrawPath( contextRef, CGPathDrawingMode.Fill)        //绘制日期文本        //先清除现有的文本        self.titleLabel?.text=""        //获取 天        let dayStr1:NSString=getUpDateStr()        let font1 = UIFont.boldSystemFontOfSize(14)        //计算文本宽度        let strSize1=dayStr1.sizeWithAttributes([NSFontAttributeName:font1])        let centerX1 = (buttonRect.size.width - strSize1.width )/2        dayStr1.drawAtPoint(CGPoint(x: centerX1, y: 0),withAttributes:  [NSFontAttributeName:font1])        //获取 星期        let dayStr2:NSString=getDownDateStr()        let font2 = UIFont.boldSystemFontOfSize(12)        let strSize2=dayStr2.sizeWithAttributes([NSFontAttributeName:font2])        let centerX2=(buttonRect.size.width-strSize2.width)/2        dayStr2.drawAtPoint(CGPoint(x: centerX2, y: buttonRect.size.height/2),withAttributes:  [NSFontAttributeName:font2])    }        func getUpDateStr()->String{        return "10-7"    }    func getDownDateStr()->String{        return "星期三"    }    }

绘制文本参考了:IOS之Quartz

绘制圆角参考了:CGContextAddArcToPoint和CGContextAddArc

1 0