⭐Unity 读取本地路径带透明通道的图片显示在Image上

在Unity中,Texture2D的默认格式可能不支持透明度,因此你需要指定一个支持透明度的格式,例如TextureFormat.ARGB32

void LoadImageFromDirectory()
{
    string directoryPath = "s/"; // 设定目录路径
    string[] files = System.IO.Directory.GetFiles(directoryPath, "*.png"); // 获取目录下所有PNG文件

    if (files.Length > 0)
    {
        string imagePath = files[0]; // 选择第一个PNG文件
        Texture2D tex = new Texture2D(2, 2, TextureFormat.ARGB32, false); // 创建Texture2D对象,使用支持透明度的格式

        if (System.IO.File.Exists(imagePath))
        {
            byte[] imageData = System.IO.File.ReadAllBytes(imagePath); // 读取图片数据
            tex.LoadImage(imageData); // 加载图片到Texture2D
            imageComponent.sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f)); // 创建Sprite并设置给Image组件
        }
        else
        {
            Debug.LogError("Failed to load image at path: " + imagePath);
        }
    }
    else
    {
    Debug.LogError("No PNG files found in directory: " + directoryPath);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值