- Home /
SetPixel() for UI Image?
Hello,
is there a way to edit pixels on UI Image? Lets say I want to make an application that has white full-screen Image and user can paint pixels on black by holding left mouse button. In the inspector I would create a UI image, set its color to white and make it stretch to full-screen. Then lets create a script.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PaintController : MonoBehaviour {
public Image screenImage; // assigned in the inspector
void Update() {
if(Input.GetMouseButton(0)) {
// and here would be something like SetPixel() that Texture2D has. Something like:
screenImage.SetPixel(Input.mousePosition.x, Input.mousePosition.y, Color.black);
}
}
}
However, Image does not contain SetPixel function so I wonder. How could I make it? Thanks for any help.
Answer by Ramazoid · May 26, 2017 at 05:13 AM
@Magnomous use material property of Image Component:
Texture2D texture = new Texture2D(512, 512);
GetComponent<Image>().material.mainTexture = texture;
and then textere.SetPixel(x,y,color)
don't forget
texture.Apply();
after all
Answer by jamesflowerdew · May 21, 2015 at 07:08 PM
errr... how about "public Texture screenImage;"?
or "public Texture2D screenImage;"
your texture would have to be read write enabled, but that would work..
also you'd have to compare mouseposition xy with screen width/height or your image gui rect stuff and then multiply by texture width/height to get proper coords for setpixxel, but other than that it should be fine :)
Thanks for response, but I don't want to use old UI. I want to have new UI Image. There must be some way of doing it.
Hi, sorry if that didn't help. As a note you don't need to use gui, it could be a 3d plane. I had a quick look at the new Image class and can see no getpixel equivlents either. Unity's global fog class has a mesh drawn to exactly match the camera in it if that's helpful. We've used getpixel both in onGUI environments and 3D meshes and using editable textures (with alpha chanels) works well. At a guess you could enginner your own Graphic class that allows texture2D input, but that sounds a bit hardcore to me.