2015-09-21 47 views
0

我想获取当前在鼠标指针下的像素颜色。如何获取当前在鼠标指针下的像素颜色

我已经拿出了这段代码,但是这并没有给出确切的位置,因为Texture2d.GetPixel不能用于float。 此代码确实给了颜色,但它并没有给出确切的鼠标位置的颜色,因为我有施展的值,因为Texture2D.GetPixel不能处理浮点整数

Texture2D texture; 
public Color ColorBelowMouse; 
public Vector3 x; 

// Use this for initialization 
void Start() 
{ 
    texture=gameObject.GetComponent<GUITexture>().texture as Texture2D; 

} 

// Update is called once per frame 
void Update() 
{ 
    Debug.Log(texture.GetPixel((int) Input.mousePosition.x, (int) Input.mousePosition.y)); 
    ColorBelowMouse=texture.GetPixel((int) Input.mousePosition.x, (int) Input.mousePosition.y); 
} 

请告诉我怎么去的颜色确切的鼠标位置。

如果我的方法错了,请告诉我正确的一个。

回答

0
Vector2 pos = Input.mousePosition; 
Camera _cam = Camera.mainCamera; 
Ray ray = _cam.ScreenPointToRay(pos); 
Physics.Raycast(_cam.transform.position, ray.direction, out hit, 10000.0f); 
Color c; 
if(hit.collider) { 
    Texture2D tex = (Texture2D)hit.collider.gameObject.renderer.material.mainTexture; // Get texture of object under mouse pointer 
    c = tex.GetPixelBilinear(hit.textureCoord2.x, hit.textureCoord2.y); // Get color from texture 
} 
+0

我试过但没有发生任何事。我无法获得任何颜色。 –

0

这似乎工作!

public Texture2D ColorPalleteImage; //Any Texture Image 
public Color ColorBelowMousePointer; 
public Rect ColorPanelWidthAndHeight; // set width and height appropriately 

void OnGUI() 
{ 
    GUI.DrawTexture(ColorPanelWidthAndHeight, ColorPalleteImage); 

    if (GUI.RepeatButton(ColorPanelWidthAndHeight, ColorPalleteImage)) 
    { 
     Vector2 pickpos = Event.current.mousePosition; 

     float aaa = pickpos.x - ColorPanelWidthAndHeight.x; 

     float bbb = pickpos.y - ColorPanelWidthAndHeight.y; 

     int aaa2 = (int)(aaa * (ColorPalleteImage.width/(ColorPanelWidthAndHeight.width + 0.0f))); 

     int bbb2 = (int)((ColorPanelWidthAndHeight.height - bbb) * (ColorPalleteImage.height/(ColorPanelWidthAndHeight.height + 0.0f))); 

     Color col = ColorPalleteImage.GetPixel(aaa2, bbb2); 

     ColorBelowMousePointer= col; 
    } 
} 
相关问题