参考转载链接:blog.csdn.net/weixin_4537...
前言
上一篇其一(scrollView),解决了如何实现一个列表的排行榜用户数据,这一篇需要解决的是头像问题,那么有几个问题卡点是需要解决的
- 如何动态指定image的src
- 如何让image变为圆形
如何动态指定image的src
在上一篇myTest.cs的基础上进行修改,需要结合编辑器
完善 InitData:
ini
private void InitData()
{
for (int i = 1; i <= 1000; ++i)
{
RankItemData data = new RankItemData();
data.rank = i;
data.name = "Name_" + i;
data.imageUrl = "假数据imageUrl";
testData.Add(data);
}
}
完善 Start 中的 SetUpdateFunc:
scss
private void Start()
{
InitData();
scrollView.SetUpdateFunc((index, rectTransform) =>
{
RankItemData data = testData[index];
rectTransform.gameObject.SetActive(true);
rectTransform.Find("rankText").GetComponent<Text>().text = data.rank.ToString();
rectTransform.Find("nameText").GetComponent<Text>().text = data.name;
Image image = rectTransform.Find("playerCover").GetComponent<Image>();
StartCoroutine(LoadPlayerImage(data.imageUrl, image));
});
}
新增
ini
private IEnumerator<object> LoadPlayerImage(string imageUrl, Image targetImage)
{
Debug.Log("imageUrl: " + imageUrl);
using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(imageUrl))
{
yield return webRequest.SendWebRequest();
if (webRequest.result != UnityWebRequest.Result.Success)
{
Debug.Log("Error loading player image: " + webRequest.error);
}
else
{
Texture2D texture = DownloadHandlerTexture.GetContent(webRequest);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), texture.width);
Debug.Log("Error loading player sprite: " + sprite);
targetImage.sprite = sprite;
}
}
}
在编辑器中,同级新增一个image组件:
StartCoroutine
是 Unity 中用于启动协程的一个方法。协程是 Unity 提供的一种特殊的编程概念,可以让你在程序中暂时"挂起"当前的执行,并在某个时间点恢复执行,适用于需要异步操作或需要等待一段时间才能执行的情况
接着 run,效果如下:
如何让image变为圆形
Mask
从网上找到的资源来看,有三种方法:Mask,Shader,顶点绘制,这里介绍前两种,因为到Shader的时候我认为已经满足了
给PlayerCover同级新增一个CoverMask,然后把PlayerCover转移到CoverMask下面变为它的子级, 并且需要给CoverMask指定一个遮罩图,这个可以自行去找一下,大概结构如下:
接着给 SetUpdateFunc 进行更新一下:
ini
scrollView.SetUpdateFunc((index, rectTransform) =>
{
RankItemData data = testData[index];
rectTransform.gameObject.SetActive(true);
rectTransform.Find("rankText").GetComponent<Text>().text = data.rank.ToString();
rectTransform.Find("nameText").GetComponent<Text>().text = data.name;
// Image image = rectTransform.Find("playerCover").GetComponent<Image>();
// StartCoroutine(LoadPlayerImage(data.imageUrl, image));
Transform coverMask = rectTransform.Find("coverMask");
if (coverMask != null)
{
Image playerCover = coverMask.Find("playerCover").GetComponent<Image>();
StartCoroutine(LoadPlayerImage(data.imageUrl, playerCover));
}
else
{
Debug.LogWarning("coverMask not found in the hierarchy");
}
});
接着就可以进行run 了,效果如下:
明显的周围有锯齿感,这是unity的knob导致,看起来就比较low了,我觉得是不满足我的预期的,因此换成下一个方法
Shader
恢复SetUpdateFunc 和 hierarchy 层级:
scss
private void Start()
{
InitData();
scrollView.SetUpdateFunc((index, rectTransform) =>
{
RankItemData data = testData[index];
rectTransform.gameObject.SetActive(true);
rectTransform.Find("rankText").GetComponent<Text>().text = data.rank.ToString();
rectTransform.Find("nameText").GetComponent<Text>().text = data.name;
Image image = rectTransform.Find("playerCover").GetComponent<Image>();
StartCoroutine(LoadPlayerImage(data.imageUrl, image));
});
}
接着需要新建一个Shader命名为UICircular,同时新建一个Material命名为Custom:
接着把UICircular拖给Custom:
UICircular:
ini
Shader "Custom/UICircular"
{
Properties
{
_R("圆的半径R", Range(0,1)) = 0.5
_Blur("边缘虚化的范围", Range(0,100)) = 100
[PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
_Color("Tint", Color) = (1,1,1,1)
_StencilComp("Stencil Comparison", Float) = 8
_Stencil("Stencil ID", Float) = 0
_StencilOp("Stencil Operation", Float) = 0
_StencilWriteMask("Stencil Write Mask", Float) = 255
_StencilReadMask("Stencil Read Mask", Float) = 255
_ColorMask("Color Mask", Float) = 15
[Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip("Use Alpha Clip", Float) = 0
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"IgnoreProjector" = "True"
"RenderType" = "Transparent"
"PreviewType" = "Plane"
"CanUseSpriteAtlas" = "True"
}
Stencil
{
Ref[_Stencil]
Comp[_StencilComp]
Pass[_StencilOp]
ReadMask[_StencilReadMask]
WriteMask[_StencilWriteMask]
}
Cull Off
Lighting Off
ZWrite Off
ZTest[unity_GUIZTestMode]
Blend SrcAlpha OneMinusSrcAlpha
ColorMask[_ColorMask]
Pass
{
Name "Default"
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
#include "UnityUI.cginc"
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
float4 worldPosition : TEXCOORD1;
UNITY_VERTEX_OUTPUT_STEREO
};
fixed4 _Color;
fixed4 _TextureSampleAdd;
float4 _ClipRect;
float _R;
float _X;
float _Y;
float _Blur;
v2f vert(appdata_t v)
{
v2f OUT;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
OUT.worldPosition = v.vertex;
OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);
OUT.texcoord = v.texcoord;
OUT.color = v.color * _Color;
return OUT;
}
sampler2D _MainTex;
fixed4 frag(v2f IN) : SV_Target
{
half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;
#ifdef UNITY_UI_CLIP_RECT
color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
#endif
#ifdef UNITY_UI_ALPHACLIP
clip(color.a - 0.001);
#endif
//圆形
float x = IN.texcoord.x - 0.5f;
float y = IN.texcoord.y - 0.5f;
float lerp = (1 - _Blur * (_R * _R - (x * x + y * y))) * color.a;//如果不加这句代码,图片边缘会有明显的锯齿
color.a = (color.a - lerp) * step(x * x + y * y, _R * _R);//如果 _R*_R<(x*x + y * y),返回 0;否则,返回 1。
return color;
}
ENDCG
}
}
}
然后根据实际调整参数,我这边的调整结果:
最后把Custom拖给PlayerCover的Material:
run起来看看效果:
这里我把之前的img替换了一下,因为之前的分辨率太大了,这里会变模糊,需要用成small size才行