iOS 中如何精准还原 Sketch 线性渐变效果

2,384 阅读1分钟

背景

image.png

这样的渐变效果当然用切图是可以方便的实现,但切图不够灵活,而且会增加包大小

那如何用代码实现呢?

首先看下 iOS 中渐变的几个参数

  • colors
  • startPoint
  • endPoint
  • locations

colors 很好获取,其他三个参数怎么办呢,似乎只能看图猜出个大概?

猜想

众所周知,sketch 有一键导出标注的插件 ,但是只能获取到 locations 信息

background-image: linear-gradient(-73deg, #361CE6 0%, #7DA7EB 50%, #96A4FF 100%);

并且这个 -73deg 对于 iOS 中的 startPoint``endPoint 来说还不太友好,需要经过一番转换。

这个时候心中有个想法💡,这个插件能导出这些信息应该是对 sketch 的源文件进行了解析,那么 sketch 的源文件是个什么样的文件呢,会不会像 .ipa 那样是个压缩包呢?

实践

file 命令可以查看文件的信息

file Test.sketch

输出如下结果

Test.sketch: Zip archive data, at least v2.0 to extract, compression method=deflate

可以看到这确实是一个压缩包

那就可以用 unzip 命令来解压一下

unzip Test.sketch -d ./temp

👀看看解压出了个啥呢?

.
├── document.json
├── meta.json
├── pages
│   └── 7832D4DC-A896-40BE-8F96-45850CE9FC53.json
├── previews
│   └── preview.png
└── user.json

有 json 文件!欣喜若狂😁!!!最终在 pages 这个目录下的 json 文件找到了想要的东西

{
	"_class": "gradient",
	"elipseLength": 0,
	"from": "{1.1356274384397782, 0.99999999999999978}",
	"gradientType": 0,
	"to": "{-0.13533980933892775, -0.49069446290249097}",
	"stops": [
		{
			"_class": "gradientStop",
			"position": 0,
			"color": {
				"_class": "color",
				"alpha": 1,
				"blue": 0.903056932532269,
				"green": 0.1092045213150163,
				"red": 0.2098672970162421
			}
		},
		{
			"_class": "gradientStop",
			"position": 0.4973543951952161,
			"color": {
				"_class": "color",
				"alpha": 1,
				"blue": 0.9204804793648098,
				"green": 0.6532974892326747,
				"red": 0.4919794574547816
			}
		},
		{
			"_class": "gradientStop",
			"position": 1,
			"color": {
				"_class": "color",
				"alpha": 1,
				"blue": 1,
				"green": 0.6418734727143864,
				"red": 0.5896740424923781
			}
		}
	]
}

结论

  • fromstartPoint
  • toendPoint
  • stops 中的 positionlocations

Tips: UI 给的 sketch 文件可能图层太多,json 文件会非常大,打开比较卡,可以把图层复制到自己新建的 sketch 文件中再解压