SHOW:
|
|
- or go back to the newest paste.
| 1 | /* Image based color picker for Unity UI by SecretAnorak Feb 2018 | |
| 2 | * 1 - Simply add this component to any UI Image to expose an "OnColorPicked" Event. | |
| 3 | * 2 - Ensure your source image (Sprite) is marked as "Read/Write Enabled" in the Texture Import Settings. | |
| 4 | * 3 - Scale the image as you like but DO NOT use preserve aspect on your image. The image must fill the entire RectTransform for this script to work.*/ | |
| 5 | ||
| 6 | using System; | |
| 7 | using UnityEngine; | |
| 8 | using UnityEngine.UI; | |
| 9 | using UnityEngine.Events; | |
| 10 | using UnityEngine.EventSystems; | |
| 11 | ||
| 12 | public class ImageColorPicker : MonoBehaviour, IPointerClickHandler | |
| 13 | {
| |
| 14 | public Color selectedColor; | |
| 15 | ||
| 16 | [Serializable] | |
| 17 | public class ColorEvent : UnityEvent<Color> { }
| |
| 18 | public ColorEvent OnColorPicked = new ColorEvent(); | |
| 19 | ||
| 20 | public void OnPointerClick(PointerEventData eventData) | |
| 21 | {
| |
| 22 | selectedColor = GetColor(GetPointerUVPosition()); | |
| 23 | OnColorPicked.Invoke(selectedColor); | |
| 24 | } | |
| 25 | ||
| 26 | private Color GetColor(Vector2 pos) | |
| 27 | {
| |
| 28 | Texture2D texture = GetComponent<Image>().sprite.texture; | |
| 29 | Color selected = texture.GetPixelBilinear(pos.x, pos.y); | |
| 30 | selected.a = 1; // force full alpha | |
| 31 | return selected; | |
| 32 | } | |
| 33 | ||
| 34 | Vector2 GetPointerUVPosition() | |
| 35 | {
| |
| 36 | Vector3[] imageCorners = new Vector3[4]; | |
| 37 | gameObject.GetComponent<RectTransform>().GetWorldCorners(imageCorners); | |
| 38 | float texWidth = imageCorners[2].x - imageCorners[0].x; | |
| 39 | float texHeight = imageCorners[2].y - imageCorners[0].y; | |
| 40 | float uvX = (Input.mousePosition.x - imageCorners[0].x) / texWidth; | |
| 41 | float uvY = (Input.mousePosition.y - imageCorners[0].y) / texHeight; | |
| 42 | return new Vector2(uvX, uvY); | |
| 43 | } | |
| 44 | } |