使用代码创建纯白图片,图片大小要与image组件大小相同
使用OnDrag触摸的时候将触摸点周围的像素都改为透明
使用shader判断两张图,只要有一张图像素点透明的地方就都透明
shader代码
Shader "Hidden/Draw"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_DrawTex ("drawtex", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType" = "Transparent" }
Blend SrcAlpha OneMinusSrcAlpha
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
sampler2D _DrawTex;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
fixed4 drawcol = tex2D(_DrawTex, i.uv);
col.a = drawcol.a == 0 ? 0 : col.a;
// just invert the colors
return col;
}
ENDCG
}
}
}
脚本代码
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()
{
}
}