Getting a sprites size in pixels

Hi guys, I’m trying to get the width / height of a sprite in pixels by doing this

_cam.WorldToScreenPoint( GetComponent().bounds.size );

this gives me a daft value of around 400 pixels high when I can see that it is no where near that size.

Am I doing something wrong here, I’ve tried a few other variations as well?

Cheers

You can use the Sprite.Rect parameter, that stores height and width in pixel

Orthograph cameras aren’t too tricky as they don’t scale with depth. You’ll need to:

  • Take the sprite bounds which are in world space (I was incorrect in my comment above)
  • Use the camera orthographic size to get the size in screen space (-2 to 2 in x and y)
  • Then scale that by the camera pixel width/height to get size in pixels

EDIT: I’ve added the 2nd approach that handles rotation.

Something like this:

		//get world space size (this version operates on the bounds of the object, so expands when rotating)
		//Vector3 world_size = GetComponent<SpriteRenderer>().bounds.size;

		//get world space size (this version handles rotating correctly)
		Vector2 sprite_size = GetComponent<SpriteRenderer>().sprite.rect.size;
		Vector2 local_sprite_size = sprite_size / GetComponent<SpriteRenderer>().sprite.pixelsPerUnit;
		Vector3 world_size = local_sprite_size;
		world_size.x *= transform.lossyScale.x;
		world_size.y *= transform.lossyScale.y;

		//convert to screen space size
		Vector3 screen_size = 0.5f * world_size / Camera.main.orthographicSize;
		screen_size.y *= Camera.main.aspect;

		//size in pixels
		Vector3 in_pixels = new Vector3(screen_size.x * Camera.main.pixelWidth, screen_size.y * Camera.main.pixelHeight, 0) * 0.5f;

		Debug.Log(string.Format("World size: {0}, Screen size: {1}, Pixel size: {2}",world_size,screen_size,in_pixels));

I suggest something like:

var originalSpriteSize = image.sprite.rect;

    image.sprite = protoSprite.ToSprite();
    image.color = protoSprite.ToGameSpriteImage().Color;

    var newSpriteSize = image.sprite.rect;

    var scaleFactorWidth = originalSpriteSize.width / newSpriteSize.width;
    var scaleFactorHeight = originalSpriteSize.height / newSpriteSize.height;

    image.transform.localScale = new Vector3(scaleFactorWidth * image.transform.localScale.x, scaleFactorHeight * image.transform.localScale.y, image.transform.localScale.z);