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

需要实现按钮如下:


大致思路:拖一个普通按钮到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 UIKit

class DateButton: UIButton {
    
    override func drawRect(rect: CGRect) {
        let buttonRect=self.layer.frame
        let contextRef = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor( contextRef,UIColor.colorWithHexString("#e83636").CGColor);
        //绘制矩形
        //CGContextMoveToPoint(contextRef,buttonRect.size.height/2);//左上
        //CGContextAddLineToPoint(contextRef,buttonRect.size.width,buttonRect.size.height/2);//右上
        //CGContextAddLineToPoint(contextRef,buttonRect.size.height);//右下
        // CGContextAddLineToPoint(contextRef,buttonRect.size.height);//左下
        //绘制下圆角矩形
        CGContextMoveToPoint(contextRef,buttonRect.size.height/2)//左上
        CGContextAddLineToPoint(contextRef,buttonRect.size.height/2)//右上
        //绘制从路径的当前点(作为开始点)到结束点(x、y)的贝塞尔曲线,其中,2,3参数定义第一个控制点的坐标;4,5定义终点坐标,最后一个是半径
        CGContextAddArcToPoint(contextRef,buttonRect.size.height,buttonRect.size.width-5,5)//右下圆角
        CGContextAddLineToPoint(contextRef,5,buttonRect.size.height)//右中
        CGContextAddArcToPoint(contextRef,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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...