美文网首页iOS开发知识小集
iOS 11以下使用 Color Set

iOS 11以下使用 Color Set

作者: 弈梦 | 来源:发表于2019-04-11 11:45 被阅读86次

    在iOS11中苹果推出了 Color Set功能,可以在Assets.xcassets中像image一样建立颜色资源,并在项目文件及Xib、Stroryboard中使用

    代码初始化color使用

    UIColor.init(named: <#String#>)
    

    storyboard/xib中使用


    image.png

    如此犀利的功能在iOS 11之下不能使用不免痛心,项目又不能只兼容到11
    观察storyboard使用颜色具体变化,主要是增加了以下代码

        <dependencies>
            // 指定了工具版本,因此低版本xcode会报错
            <capability name="Named colors" minToolsVersion="9.0"/>
        </dependencies>
      
        <!-- 普通的颜色引用方式
        <color key="textColor" red="0.066666666669999999" green="0.066666666669999999" blue="0.066666666669999999" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
        -->
    
         // Named Color引用颜色的方式
        <color key="textColor" name="primary"/>
    
        // 引用的颜色资源
        <resources>
            <namedColor name="primary">
                <color red="0.90200001001358032" green="0.0" blue="0.071000002324581146" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
            </namedColor>
        </resources>
    

    所以解决思路就是使用脚本,在编译的时候将xml中的颜色标签替换掉,以下是python脚本

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os, json, argparse
    
    print os.getcwd()
    
    parser = argparse.ArgumentParser(description='Convert color assets from storyboards and xibs')
    parser.add_argument('--colorSpace', dest="color_space",
              type=str,
              default="calibratedRGB",
              nargs='?',
              help="Default colorSpace string (default: calibratedRGB)") #calibratedRGB
    
    colorDict = {}
    
    def custom_color_space(space):
        return 'colorSpace="custom" customColorSpace="{}"'.format(space)
    
    args = parser.parse_args()
    
    colorSpaceMap = {
        'calibratedrgb': 'colorSpace="calibratedRGB"',
        'srgb': custom_color_space("sRGB"),
        'displayP3': custom_color_space("displayP3"),
        'calibratedwhite': custom_color_space("calibratedWhite"),
    }
    
    defaultColorSpace = colorSpaceMap.get(args.color_space.lower())
    
    # read all colorset
    for root, dirs, files in os.walk("./"):
        for d in dirs:
            if d.endswith(".colorset"):
                colorK = d.split(".")[0]
                print "found " + colorK
                for file in files:
                    if file == "Contents.json":
                        f = open(os.path.join(root, d, file))
                        jd = json.load(f)
                        color = jd["colors"][0]["color"]
                        rgb = color["components"]
                        colorSpace = color["color-space"]
                        if not colorSpace:
                            colorSpace = defaultColorSpace
                        else:
                            colorSpace = colorSpaceMap.get(colorSpace)
    
                        colorDict[colorK] = 'name="{}" red="{}" green="{}" blue="{}" alpha="{}" {}'.format(colorK, rgb["red"], rgb["green"], rgb["blue"], rgb["alpha"], colorSpace)
    
    print ""
    import re
    
    # replacing
    for root, dirs, files in os.walk("./"):
        for file in files:
            if file.endswith((".storyboard", ".xib")):
                path = os.path.join(root, file)
                print "Replacing namedColor in " + path
                f = open(path)
                nf = f.read()
                f.close()
                nf = re.sub(r" +<namedColor name=.*\n.*\n +</namedColor>\n", '', nf)
                nf = re.sub(r" +<capability name=\"Named colors\" minToolsVersion=\".*\n", '', nf)
    
                for k, v in colorDict.items():
                    nf = re.sub(r'name="{}"/>'.format(k), v + "/>", nf)
    
                f = open(path, 'w')
                f.write(nf)
                f.close()
    

    脚本的作用是移除了capability和namedColor标签,然后对所有的color标签进行了替换,替换后的效果是

     <color key="textColor" name="primary" red="0.902" green="0.000" blue="0.071" alpha="1.000" colorSpace="custom" customColorSpace="sRGB"/>
    

    使用方法: 将脚本文件放置在项目文件目录下,然后在build phases下新建一个Run Script,编译的时候执行即可

    相关文章

      网友评论

        本文标题:iOS 11以下使用 Color Set

        本文链接:https://www.haomeiwen.com/subject/pqftwqtx.html