Unity realizes the brush function (you draw, I guess, scratch, etc.)

 

code show as below: 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Drawonimage : MonoBehaviour, IDragHandler
{
    public Texture tu;
    public int r = 5;
    Texture2D texture;
    Vector2 wh;
    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos = transform.InverseTransformPoint(eventData.position);
        Debug.Log(pos);
        Vector2Int v2 = new Vector2Int((int)(pos.x + wh.x / 2), (int)(pos.y + wh.y / 2));
        int wbegin = v2.x - r;
        wbegin = wbegin > 0 ? wbegin : 0;
        int wend = v2.x + r;
        wend = wend < (int)wh.x ? wend : (int)wh.x;
        int hbegin = v2.y - r;
        hbegin = hbegin > 0 ? hbegin : 0;
        int hend = v2.y + r;
        hend = hend < (int)wh.y ? hend : (int)wh.y;

        for (int x = wbegin; x < wend; x++)
        {
            for (int y = hbegin; y < hend; y++)
            {
                if (Vector2.Distance(v2, new Vector2(x, y)) <= r)
                {
                    texture.SetPixel(x, y, new Color(1, 1, 1, 0));
                }
            }
        }
        texture.Apply();
    }

    // Start is called before the first frame update
    void Start()
    {
        wh = GetComponent<RectTransform>().sizeDelta;
        texture = new Texture2D((int)wh.x, (int)wh.y);
        for (int x = 0; x < wh.x; x++)
        {
            for (int y = 0; y < wh.y; y++)
            {
                texture.SetPixel(x, y, Color.white);
            }
        }
        texture.Apply();
        Material material = new Material(Shader.Find("Hidden/Draw"));
        material.SetTexture("_MainTex", tu);
        material.SetTexture("_DrawTex", texture);
        GetComponent<Image>().material = material;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

 

Guess you like

Origin blog.csdn.net/q1295006114/article/details/130800355