[英]Unity 2D : Get pixel of color of Raw Image
我想知道如何获得 rawImage 纹理的像素颜色。
这是我的场景:
public class ColorPicker : MonoBehaviour, IPointerClickHandler
{
public GameObject Cube;
public void OnPointerClick(PointerEventData eventData)
{
if (Input.GetMouseButtonUp(1))
{
Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);
Color color = (GetComponent<RawImage>().texture as Texture2D).GetPixel(Convert.ToInt32(localPosition.x),
Convert.ToInt32(localPosition.y));
Cube.GetComponent<Renderer>().material.color = color;
}
}
}
正如您所看到的,使用此代码,它可以工作但没有被调用。
事实上,我无法达到蓝色。 我只能得到我的正方形的顶部。
你能帮我按右键时如何获得颜色吗?
谢谢
您使用的鼠标位置
Input.mousePosition
在屏幕空间中(意味着你得到的位置是相对于屏幕尺寸的)。
你想要得到的是鼠标在画布空间中的位置(相对于画布大小,所以你不必担心画布大小)。
您可以通过在 ColorPicker 脚本中实现 IPointerClickHandler 来做到这一点(这也是比使用 Input.mousePosition 更好的做法)。
using UnityEngine.EventSystems;
public class ColorPicker : MonoBehaviour, IPointerClickHandler{
public GameObject Cube;
void OnPointerClick(PointerEventData eventData)
{
//eventData.position
//Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);
//ignore z coordinate
}
}
PointerEventData 包含很多有用的信息,您可以在统一文档https://docs.unity3d.com/ScriptReference/EventSystems.PointerEventData.html 中获取更多信息
您可能仍然需要使用
transform.InverseTransformPoint(eventData.pressPosition);
因为我还没有测试过。 但我希望这为您指明了正确的方向!
尝试将其转换为2DTexture
,然后您可以使用Texture2D.GetPixels
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.