c# - 重新运行程序,得到不同的结果 C# UWP vs2019
问题描述
问题解决了。请参阅下面 FayWang 的评论。
添加信息。
行。我添加了一些代码来删除项目。删除(一次一个)。当看到一个图像时..所有 25 个图像都被创建到同一个位置。问题是在 Sub 中创建新图像。其中一些没有图像,例如未设置源。没有解释为什么它们都有相同的坐标。然后下一个负载可能会正常工作,也可能不会。
我可能会觉得自己很愚蠢,但是......
我刚刚构建了一个快速而简短的程序(C# UWP VS 2019)。它将在屏幕上构建 25 个图像。我打算添加一个全部删除按钮(试图找到内存泄漏)并将它们添加回来,但从来没有那么远。
该程序编译没有错误。我运行它。通常,我看到的不是 25 张图片,而是 1 张。在第一次运行时。再次运行它(没有重建或代码更改),我可能会得到 25。我不知道会发生什么。
在最后一次构建之后,在 10 次运行中,我得到了 1、25、1、25、25、1、25、25、25、1
此外,在 1 张图片上。他们似乎在不同的地方。
我将完整的代码放在下面。我经常犯错误。但这只是重新运行代码。
另外,我今天早上也刚刚重新安装了 Visual Studio。
首先是 Page 标记内的 Xaml,然后是后面的代码
<Grid>
<Canvas x:Name="MyCanvas">
<Rectangle x:Name="CutCopyRect"
Height="980" Width="1480"
Fill="LemonChiffon"
Canvas.Left="10" Canvas.Top="10"/>
</Canvas>
public MainPage()
{ this.InitializeComponent();
DrawSomeImages();
}
void DrawSomeImages()
{for (int iCt1 = 0; iCt1 < 5; iCt1++)
{ for (int iCt2 = 0; iCt2 < 5; iCt2++)
{ makeImage(iCt1, iCt2); }
}
}
void makeImage(int inTop, int inLeft)
{ try
{
Image img1 = new Image();
img1.Source = new BitmapImage(new Uri("ms-appx:///Assets/SmileyAngry.png"));
img1.Width = 220;
img1.Height = 220;
img1.SetValue(Canvas.TopProperty, (inTop * 38));
img1.SetValue(Canvas.LeftProperty, (inLeft * 39));
MyCanvas.Children.Add(img1);
}
catch (Exception ex)
{
string thisProc = System.Reflection.MethodBase.GetCurrentMethod().ToString();
Debug.WriteLine("Error Message: ", ex.Message, " In " + thisProc);
}
}
解决方案
当显式设置图像的宽度时,最好设置BitmapImage 的DecodePixelWidth属性。它将加载具有指定宽度的 BitmapImage。有助于加载大图像时的内存使用和速度。
Image img1 = new Image();
BitmapImage bi = new BitmapImage(new Uri(this.BaseUri, "ms-appx:///Assets/Logo.png"));
img1.Width = bi.DecodePixelWidth = 110;
img1.Height = bi.DecodePixelHeight = 110;
img1.SetValue(Canvas.TopProperty, (inTop * 38));
img1.SetValue(Canvas.LeftProperty, (inLeft * 39));
img1.Source = bi;
MyCanvas.Children.Add(img1);
推荐阅读
- android - 如何将我的应用快捷方式添加到通知面板
- python - 如何从特定行和列python的单元格中检索值?
- c++ - 在 C++ 中获取线程 ID
- angular - 以角度测试 post 方法
- python - Python linter 警告:签名与基本方法不匹配
- vue.js - Vuejs中未刷新字段
- python - Django文件上传为不同的用户
- php - Laravel Eloquent sum on realtions
- datastax - 为 Apache TinkerPop 的 Spark-Gremlin 指定工作池 - DataStax-Enterprise Graph-Analytics
- json - 如何将此复杂 Json 转换为 Dart 对象