SetPixel() for UI Image?


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,;

However, Image does not contain SetPixel function so I wonder. How could I make it?
Thanks for any help.

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


after all

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 :slight_smile: