set a GUI Texture to Fit a UI panel

I have a panel with a GUI texture is been created by code as this :

GUITexture background=gameObject.AddComponent<GUITexture>();

How can i make this GUITexture to Fit a Panel inside a canvas No matter what the screen width or height are i am trying this code but it does not work :

GUITexture background=gameObject.AddComponent<GUITexture>();
Image img = gameObject.GetComponent<Image>();
Vector3 posStart=Camera.Main.WorldtoScreenPoit(img.RectTransform.anchorMin.x,img.RectTransform.anchorMin.y,0);
Vector3 posEnd=Camera.Main.WorldtoScreenPoit(img.RectTransform.anchorMax.x,img.RectTransform.anchorMax.y,0);

int widthX = (int)(posEnd.x - posStart.x);
int widthY = (int)(posEnd.y - posStart.y);

GUITexture.PixelInset= new Rect(posStart.x,posStart.y,widthX,widthY);

I am sorry if any syntax error may occur as i didn’t copy and past the code

the code that i am using should scale the gui texture based on the UI panel RectTransform

but this is how the view is looking like

41709-untitled.png

the canvas is set to fit the screen resolution (width and height) , but as you can see th GUITexture is not fitting the UI Panel ,what i am doing wrong

PS: The GUITexture is being used as a WebcamTexture , i am using a GUITexture over a panel for the sake of the responsiveness between multiple devices, i was using a plane , but i did not know how to resize it based on screen width and height

Why not just change the texture to a sprite and set it as the background for the panel, should size it automatically. Just select the the Texture and where it says Texture in the inspector open the drop down and select Sprite UI/2D but that’s from memory as I don’t have access to Unity at the moment.

Mixing legacy and new UI looks like a bad idea.

I’ve never done this, but I guess it should work:

  1. Create a Texture2D with your webcam output
  2. Create a Sprite with that texture: Unity - Scripting API: Sprite.Create
  3. Set the sprite as the “source image” of the Image component of the panel

When you add an Image component to some UI object, the sprite will expand or shrink to fit in. You can set up how the sprite is stretched (if it’s a sliced sprite or not, if it should preseve aspect ratio, etc). I guess you can do all this with code.