0

我正在尝试从我的 ViewModel 渲染画布。将画布传递给我的虚拟机后,我使用此函数对其进行渲染:

private void GenerateTextures(object obj)
{
    if (!(obj is UIElement))
        return;

    UIElement control = (UIElement)obj;

    for (int i = 0; i <= _textureCount - 1; ++i)
    {
        string path = OutPath + i.ToString() + TextureFormat;
        FontText = i.ToString();

        using (FileStream fs = new FileStream(path,FileMode.Create))
        {
            control.Measure(new Size(_textureSize, _textureSize));
            //control.Measure(size);
            control.Arrange(new Rect(new Size(_textureSize, _textureSize)));
            control.UpdateLayout();

            RenderTargetBitmap bitmap = new RenderTargetBitmap(_textureSize, _textureSize, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(control);
            BitmapEncoder encoder;
            switch (TextureFormat)
            {
                case ".png":
                    encoder = new PngBitmapEncoder();
                    break;
                case ".jpg":
                    encoder = new JpegBitmapEncoder();
                    break;
                case ".gif":
                    encoder = new GifBitmapEncoder();
                    break;
                default:
                    encoder = new PngBitmapEncoder();
                    break;
            }

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(fs);
        }
    }
}

这工作正常,除了安排()函数之外的所有功能都会导致我的画布移动到其父级的左上角,这在视觉上破坏了我的 UI。如果我删除对arrange() 的调用,那么我渲染的位图只是cavas 的一个小角落。

如何在不移动 UI 的情况下渲染我的卡瓦斯?

4

1 回答 1

0

我认为您应该在安排 Canvas 时指定它的位置。您可以使用以下构造函数Rect

公共矩形(点位置,大小大小);

所以你的代码可能是这样的:

control.Arrange(new Rect(new Point(X,Y), new Size(_textureSize, _textureSize)));

此外,一旦父布局发生更改或更新,您应该调用度量和排列代码。

于 2017-11-28T06:48:04.027 回答