/** * Calculate UV of given position on a rendered texture given the border. * Returned value is [(0,0)..(textureWidth,textureHeight)]. */ public static Vector2 PixelToUV(Rect drawRect, Rect textureRect, Vector2 position, RectOffset border = null) { position -= drawRect.min; drawRect.x = 0; drawRect.y = 0; if ((border == null) || border.IsZero()) { if ((drawRect.width == 0f) || (drawRect.height == 0f)) { return(Vector2.zero); } Vector2 result = new Vector2(); result.x = textureRect.x + (position.x / drawRect.width * textureRect.width); result.y = textureRect.y + (position.y / drawRect.height * textureRect.height); return(result); } Rect innerRect = border.Remove(drawRect); Rect innerTexture = border.Remove(textureRect); float x; float y; if (position.x <= innerRect.xMin) { x = position.x; } else if (position.x >= innerRect.xMax) { x = (textureRect.xMax - (drawRect.width - position.x)); } else { if (innerRect.width == 0) { x = innerTexture.xMin; } else { x = ((position.x - innerRect.xMin) / innerRect.width) * innerTexture.width + innerTexture.xMin; } } if (position.y <= innerRect.yMin) { y = position.y; } else if (position.y >= innerRect.yMax) { y = (textureRect.yMax - (drawRect.yMax - position.y)); } else { if (innerRect.height == 0) { y = innerTexture.yMin; } else { y = ((position.y - innerRect.yMin) / innerRect.height) * innerTexture.height + innerTexture.yMin; } } return(new Vector2(x, y)); }