【Unity】贴图主色调及其明度自动计算工具

来源:互联网 发布:二叉树的中序遍历算法 编辑:程序博客网 时间:2024/06/08 08:39

前言


来自家装设计师的需求:想知道贴图的主色调和明度。

于是用Unity开发了这个小工具。


完整工程场景及代码:参见原文后续评论。

最终效果


左边是算出的主色调,右边是原始贴图


源代码

using UnityEngine;using UnityEngine.UI;using System.Collections;/// <summary>/// 贴图主色调及明度计算工具/// Created by 杜子兮 2016.1.23/// duzixi.com All Rights Reserved/// </summary>public class MainColor : MonoBehaviour {public Texture2D img;public RawImage orgTexture;public Image mainColor;public Text colorValue;// 按下空格时开始计算void Update () {if (Input.GetKeyDown(KeyCode.Space)) {ComputeMainColor();}}// 计算主色调void ComputeMainColor() {float r = 0;float g = 0;float b = 0;int width = img.width;int height = img.height;Color[] colors = new Color[width * height];for (int i = 0; i < width; i++) {for (int j = 0; j < height; j++) {colors[i * height + j] = img.GetPixel(i, j);r += colors[i * height + j].r;g += colors[i * height + j].g;b += colors[i * height + j].b;}}r /= width * height;g /= width * height;b /= width * height;// 计算明度float v = Mathf.Max (Mathf.Max (r, g), b);orgTexture.texture = img;mainColor.color = new Color (r, g, b);colorValue.text = "主色调明度:" + v + " \n 色值:(" + r * 255 + "," + g * 255 + "," + b * 255 + ")";}}


后语

本来以为O(n*n)复杂度算法略复杂,一开始用的随机采样,但效果并不理想。

后来在超哥指点下干脆遍历所有点,结果在PC上就是秒算,效果也很令人满意。

0 0