昨天在改项目的时候,看到人物头像是圆形的,我就想到用UGUI的Mask组件,但是我试了一下,效果不是很好,而且性能上也不是很理想,所以我就找到一个比较好的解决办法,之前也考虑过用Image上的Material去弄,但是也不是很完美,后来看到一篇文章,说是重写Image组件,所以就有了下面我要提到的东西(只支持5.3版本以上)。
首先需要重写Image,由于继承UnityEngine基类的派生类不能在Inspector里显示自定义参数。所以我们要新建BaseImage类来代替Image类。原Image源码有近千行代码,BaseImage对其进行了部分精简,只支持Simple Image Type,并去掉了eventAlphaThreshold的相关代码。经过删减,得到一个百行代码的BaseImage类,精简版Image就完成了。
using System;
using UnityEngine;
using System.Collections;
using UnityEngine.Serialization;
using UnityEngine.UI;
public class BaseImage : MaskableGraphic,ISerializationCallbackReceiver, ILayoutElement, ICanvasRaycastFilter
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
[FormerlySerializedAs("m_Frame")]
[SerializeField]
private Sprite m_Sprite;
public Sprite sprite { get { return m_Sprite; } set { if (SetPropertyUtilityExt.SetClass(ref m_Sprite, value)) SetAllDirty(); } }
[NonSerialized]
private Sprite m_OverrideSprite;
public Sprite overrideSprite { get { return m_OverrideSprite == null ? sprite : m_OverrideSprite; } set { if (SetPropertyUtilityExt.SetClass(ref m_OverrideSprite, value)) SetAllDirty(); } }
/// <summary>
/// Image's texture comes from the UnityEngine.Image.
/// </summary>
public override Texture mainTexture
{
get
{
return overrideSprite == null ? s_WhiteTexture : overrideSprite.texture;
}
}
public float pixelsPerUnit
{
get
{
float spritePixelsPerUnit = 100;
if (sprite)
spritePixelsPerUnit = sprite.pixelsPerUnit;
float referencePixelsPerUnit = 100;
if (canvas)
referencePixelsPerUnit = canvas.referencePixelsPerUnit;
return spritePixelsPerUnit / referencePixelsPerUnit;
}
}
/// <summary>
/// 子类需要重写该方法来自定义Image形状
/// </summary>
/// <param name="vh"></param>
protected override void OnPopulateMesh(VertexHelper vh)
{
base.OnPopulateMesh(vh);
}
#region ISerializationCallbackReceiver
public void OnAfterDeserialize()
{
}
//
// 摘要:
// Implement this