是否可以直接向相机显示图像?

Yuv*_*mir -2 unity-game-engine

我需要能够在运行时逐个像素地编辑图像,并拥有一个将其视图替换为图像的相机。是否可以?

use*_*449 6

绝对有可能。通过SetPixels将纹理组合并设置为Read Write Enabled,您可以写入纹理并操作数据。我不确定你的意思

是否将其视图替换为图像

这是我如何解决您的问题

// color we are setting pixels to
[SerializeField] private Color clr = Color.white;

// our source UI image - it can be a raw image or sprite renderer, I just used UI image
[SerializeField] private Image img = null;

// the size of our 'brush'
[Range(1, 100)]
[SerializeField] private int BrushSize = 1;

// the texture we are going to manipulate
private Texture2D tex2D = null;

private void Awake()
{
    Sprite imgSprite = img.sprite;

    // create a new instance of our texture to not write to it directly and overwrite it
    tex2D = new Texture2D((int)imgSprite.rect.width, (int)imgSprite.rect.height);
    var pixels = imgSprite.texture.GetPixels((int)imgSprite.textureRect.x,
                                            (int)imgSprite.textureRect.y,
                                            (int)imgSprite.textureRect.width,
                                            (int)imgSprite.textureRect.height);
    tex2D.SetPixels(pixels);
    tex2D.Apply();

    // assign this new texture to our image by creating a new sprite
    img.sprite = Sprite.Create(tex2D, img.sprite.rect, img.sprite.pivot);
}

public void OnDrag(PointerEventData eventData)
{
    Vector2 localCursor;

    // convert the position click to a local position on our rect
    if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(img.rectTransform, eventData.position, eventData.pressEventCamera, out localCursor))
        return;

    // convert this position to pixel coordinates on our texture
    int px = Mathf.Clamp(0, (int)((localCursor.x - img.rectTransform.rect.x) * tex2D.width / img.rectTransform.rect.width), tex2D.width);
    int py = Mathf.Clamp(0, (int)((localCursor.y - img.rectTransform.rect.y) * tex2D.height / img.rectTransform.rect.height), tex2D.height);

    // debugging - you can remove this
    print(px + ", " + py);


    // if our brush size is greater than 1, then we need to grab neighbors
    if (BrushSize > 1)
    {
        // create an array for our colors
        Color[] colorArray = new Color[BrushSize * BrushSize];

        // fill this with our color
        for(int x = 0; x < BrushSize * BrushSize; ++x)
            colorArray[x] = clr;

        tex2D.SetPixels(px, py, BrushSize, BrushSize, colorArray);
    }
    else
    {
        // set our color at our position
        tex2D.SetPixel(px, py, clr);
    }

    // apply the changes
    tex2D.Apply();

    // set our sprite to the new texture data
    img.sprite = Sprite.Create(tex2D, img.sprite.rect, img.sprite.pivot);
}
Run Code Online (Sandbox Code Playgroud)

这是正在运行的代码片段。我没有考虑一些错误处理,例如使用SetPixels. 当前画笔也是底部左对齐,可以更改为居中。由于您没有添加自己的任何进度,我会让您清理实现并根据您的用例需要更改它。

例子

为清楚起见,这里是纹理的导入设置。

导入设置