Question by
Lazybones94 · Nov 06, 2015 at 09:32 AM ·
aspect ratiogetpixel
Preserve aspect and getPixel
Hello everyone. In my project I managed to get pixel of an UI image under the mouse position with help of folowing code:
//find out the min and max coordinates of the rect in screen coordinates
coordMin = Camera.main.WorldToScreenPoint(myImage.TransformPoint(myImage.rect.min));
coordMax = Camera.main.WorldToScreenPoint(myImage.TransformPoint(myImage.rect.max));
imageSize = coordMax - coordMin;
//get the point where we clicked on the image coordinates
coordX = Input.mousePosition.x - coordMin.x;
coordY = Input.mousePosition.y - coordMin.y;
//get the float part of the image position that we clicked on(e.g. we clicked on the center,
//we get 0.5 of image)
Xpart = 1 / (imageSize.x / coordX);
Ypart = 1 / (imageSize.y / coordY);
if (Xpart < 0 || Xpart > 1 || Ypart < 0 || Ypart > 1) return;
//we do not need to proceed if player did not click on the image rect
//mySprite is attached to myImage
posX = (int)(mySprite.texture.width * Xpart);
posY = (int)(mySprite.texture.height * Ypart);
if ((posX > 0 && posY > 0))
{
if (posX < mySprite.texture.width && posY < mySprite.texture.height)
{
if (mySprite.texture.GetPixel(posX, posY).a != 0)
{
myAnotherImage.color = mySprite.texture.GetPixel(posX, posY);
}
}
}
But this code only works when image is set to not preserve aspect ratio. I can't calculate the coordinates because when preserve aspect ratio is on the texture pixels have other coordinates. How do I get pixels when image preserves aspect ratio?
Comment