我想知道如何获得 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;
}
}
}
如您所见,使用这段代码,它可以工作,但不会被调用。
其实我是够不到蓝色的。我只能得到我方 block 的顶部。
你能帮我如何在我按下右键时获得颜色吗?
谢谢
最佳答案
您使用的鼠标位置
Input.mousePosition
在屏幕空间中(意味着您获得的位置是相对于屏幕尺寸的)。
你要获取的是鼠标在 Canvas 空间中的位置(相对于 Canvas 大小,所以不用担心 Canvas 大小)。
您可以通过在 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);
因为我还没有测试过这个。但我希望这能为您指明正确的方向!
关于c# - 统一二维 : Get pixel of color of Raw Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550008/