实现圆角矩形,根据这位大哥的文章:Unity shader 实现圆角矩形
但是如果图片不是正方形的时候,就会出现以下情况
因为图片的texture,长和宽是不等长的。如果想事现圆角是等距离的,需要在计算圆心的时候乘一下图片的长宽比
float aspectRatio = width/height;
if(aspectRatio>1){
newUv.x*=aspectRatio;
roundCenter= float2(0.5*aspectRatio - _RADIUS,0.5 - _RADIUS);
}else{
newUv.y*=1/aspectRatio;
roundCenter= float2(0.5 - _RADIUS,0.5*(1/aspectRatio) - _RADIUS);
}
这样就可以是等距的圆角矩形了
shader 链接
shader 代码
Shader "zynTest/RoundShader"
{
Properties
{
[HideInInspector]
_MainTex ("Base(RGB)", 2D) = "white" {}
_RADIUS("radius",Range(0,0.5))=0.2
[Toggle] _USEEQUALLYROUND ("是否使用等距的圆角", Float) = 0
}
SubShader
{
Pass
{
Tags
{
"RenderType"="Transparent"
"Queue" = "Transparent"
"IgnoreProjector" = "True"
}
// LOD 100
ZTest On
ZWrite On
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers gles
#include "UnityCG.cginc"
float _RADIUS;
struct v2f
{
float2 uv : TEXCOORD0;
float2 RadiusBuceVU: TEXCOORD1;
float4 pos : SV_POSITION;
};
sampler2D _MainTex;
//纹理 宽高 _TexelSize = float(1/x像素,1/y像素,x像素,y像素);
float4 _MainTex_TexelSize;
float _USEEQUALLYROUND;
v2f vert (appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord;
return o;
}
fixed4 frag (v2f i) : COLOR
{
fixed4 col;
col = tex2D(_MainTex, i.uv);
//纹理 宽高
float width = _MainTex_TexelSize.z;
float height = _MainTex_TexelSize.w;
float2 newUv =i.uv - float2(0.5, 0.5);
float2 roundCenter =(0.5 - _RADIUS,0.5 - _RADIUS);
if(_USEEQUALLYROUND>0){
float aspectRatio = width/height;
if(aspectRatio>1){
newUv.x*=aspectRatio;
roundCenter= float2(0.5*aspectRatio - _RADIUS,0.5 - _RADIUS);
}else{
newUv.y*=1/aspectRatio;
roundCenter= float2(0.5 - _RADIUS,0.5*(1/aspectRatio) - _RADIUS);
}
}
if(abs(newUv.x)<roundCenter.x || abs(newUv.y)<roundCenter.y ){
}else{
if (length(abs(newUv) - roundCenter) < _RADIUS){
}else{
discard;
}
}
return col;
}
ENDCG
}
}
}