【问题标题】:Image not visible in a custom canvas (derived class of Canvas)图像在自定义画布中不可见(画布的派生类)
【发布时间】:2011-12-30 21:37:37
【问题描述】:

我在应用程序中有一个自定义画布,它没有显示图像,在 XAML 中,我写道:

<local:MyCanvas>
    <local:MyCanvas.LayoutTransform>
        <ScaleTransform x:Name="scale"  ScaleX="1" ScaleY="1" />
    </local:MyCanvas.LayoutTransform>
    <Image Source="C:\abc.jpg" />
</local:MyCanvas>

我在Canvas上试过了,也可以,但是在派生类中没有出现,但是Visual Studio显示了轮廓,意思是图片已经添加了。

作为替代方案,在 MyCanvas:Canvas 类中,我输入:

Image img = new Image();
img.Width = 200;

BitmapImage myBitmapImage = new BitmapImage();

myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\abc.jpg");

myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();

img.Source = myBitmapImage;

this.Children.Add(img);

仍然不可见。有什么想法吗?

【问题讨论】:

  • 这可能是您的MyCanvas 类中的某个问题。如果您从课程中删除所有内容,您是否仍然看到问题,所以它只是 public class MyClass : Canvas {}
  • 您确定图像存在于提供的路径中吗? (有时是简单的事情......)
  • 是的,否则 Visual Studio 会自动报错。为了确定,我再次检查了它。

标签: c# .net wpf image wpf-controls


【解决方案1】:

我一直在尝试不同的东西,我已经能够通过将图像包含在 DrawingVisual 中来添加它,这里是代码:

private void addImage (DrawingContext dc)
{
BitmapImage bi = new BitmapImage();

bi.BeginInit();
bi.UriSource = new Uri(@"C:/abc.jpg");
bi.EndInit();

dc.DrawImage(bi, new Rect(new Point(0,0), new Point(200,200)));
}

然后将 DrawingVisual 添加到自定义 Canvas,代码如下:

DrawingVisual abc = new DrawingVisual();
DrawingContext dc = abc.RenderOpen ();
addImage (dc)
dc.Close();

base.AddVisualChild(abc);
base.addLogicalChild(abc);

使用此方法,图像可见,并且工作正常。

但是为什么不使用之前的方法添加到 MyCanvas 中呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多