zoukankan      html  css  js  c++  java
  • 想制作纯色的UIButton吗? 来,哥教你~

    因为项目要做到美观,加上扁平化设计这么流行,所以各种找资料.

    原本想找找UIButton是否有直接的设置方法,却发现没有.找到点击后高亮也只有setBackgroundImage 这条路走了.
    首先写一个能改变大小,颜色,返回值为image的类方法.(我在网上找的...)
    + (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
        
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
        UIGraphicsBeginImageContext(rect.size);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [color CGColor]);
        
        CGContextFillRect(context, rect);
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        return image;
        
    }
    好吧,以下是我写的,与君分享:
    + (instancetype)buttonWithTitleAndColor:(NSString *)title frame:(CGRect)frame
    {
    //必须是UIButtonTypeCustom,否则设置高亮不起作用
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn.layer setMasksToBounds:YES];
        [btn.layer setCornerRadius:4.0]; //设置矩形四个圆角半径
    //    [btn.layer setBorderWidth:1.0]; //边框宽度
        btn.frame = frame;
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //ButtonBgColor与ButtonTouchBgColor是两个UIColor颜色的宏定义,大家可以随意定义.例如[UIColor blueColor];
        UIImage * bgImage1 = [self imageWithColor:ButtonBgColor size:frame.size];
        UIImage * bgImage2 = [self imageWithColor:ButtonTouchBgColor size:frame.size];
        [btn setBackgroundImage:bgImage1 forState:UIControlStateNormal];
        [btn setBackgroundImage:bgImage2 forState:UIControlStateHighlighted];
        
        return btn;
    }
    大家也可以根据CAlayer的属性和方法,自定义喜欢的UIButton样式.
     
  • 相关阅读:
    error: expected unqualified-id extern "C" {
    cmake交叉编译android(转)
    wwindows文件放入linux后多出换行符
    JNI 引用问题梳理(转)
    OpenCV实现任意大小图片的合并(转)
    android camera preview常用格式
    Linux下找不到动态链接库(转)
    ld链接器的工作原理及链接顺序(转)
    添加静态库入动态库时,符号查找不到的问题
    如何捕获 System.loadLibrary 产生的异常?(转)
  • 原文地址:https://www.cnblogs.com/xclidongbo/p/4096238.html
Copyright © 2011-2022 走看看