使用Texture2D.SetPixelData将所有像素设置为红色(255,0,0),但像素更改为多色分类

问题描述 投票:0回答:1

我有以下代码:

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()
    {
        
    }
}

产生这个:

The image produced by aforementioned code.

我不确定是什么产生了它。以前我使用字节数组进行测试,效果很好,但我的工作现在需要一个队列,然后将该队列转换为数组(我已经使用 .ToArray() 完成了)。

我还使用了 RGBA32 而不是 RGB24,其 alpha 值为 255、128、1 和 0;然而,这每次都会产生几乎透明的图像。

谢谢您的帮助。

c# unity-game-engine textures texture2d
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

© www.soinside.com 2019 - 2024. All rights reserved.