我有以下代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextureScript : MonoBehaviour
{
Texture2D texture;
// Start is called before the first frame update
void Start()
{
texture = new Texture2D(256,256, TextureFormat.RGB24, true);
var rectTransform = transform.GetComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(texture.width, texture.height);
int pixelCount = texture.width * texture.height;
Queue<Color> queue = new Queue<Color>();
for(int i = 0; i < pixelCount; i++)
{
queue.Enqueue(new Color(255,0,0));
}
Color[] colorArray = queue.ToArray();
texture.SetPixelData(colorArray, 0, 0);
texture.filterMode = FilterMode.Point;
texture.Apply(updateMipmaps: false);
GetComponent<RawImage>().material.mainTexture = texture;
}
// Update is called once per frame
void Update()
{
}
}
产生这个:
我不确定是什么产生了它。以前我使用字节数组进行测试,效果很好,但我的工作现在需要一个队列,然后将该队列转换为数组(我已经使用 .ToArray() 完成了)。
我还使用了 RGBA32 而不是 RGB24,其 alpha 值为 255、128、1 和 0;然而,这每次都会产生几乎透明的图像。
谢谢您的帮助。
说实话,我不知道那里到底发生了什么,但是
Queue
而不是简单地使用数组?SetPixelData
而不是简单地使用 SetPixels
?我会简单地做例如
//var pixels = texture.GetPixels();
// or even simply
var pixels = new Color[texture.width * texture.height];
for(var i = 0; i < pixels.Length; i++)
{
pixels[i] = color.Red;
}
texture.SetPixels(pixels);
texture.Apply();
SetPixelData
相当
如果您想将压缩或其他非颜色纹理格式数据加载到纹理中,则非常有用。
还请注意
new Color(255,0,0)
Color
采用从 0
到 1
的 float参数。如果您正在寻找基于字节的输入,请选择
Color32
和 SetPixels32