为什么图片加载不出来?
分裂图片--一张照片放进BitmapImage里面然后利用WriteableBitmap将图片分成4块
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Name="imgUL" Grid.Row="0" Grid.Column="0" Margin="2"/>
<Image Name="imgUR" Grid.Row="0" Grid.Column="1" Margin="2"/>
<Image Name="imgLL" Grid.Row="1" Grid.Column="0" Margin="2"/>
<Image Name="imgLR" Grid.Row="1" Grid.Column="1" Margin="2"/>
</Grid>
int picturewidth;
int pictureheight;
public MainPage()
{
InitializeComponent();
picturewidth =((int)ContentPanel.ActualWidth)- 8;
pictureheight = ((int)ContentPanel.ActualHeight) - 8;
// 用于本地化 ApplicationBar 的示例代码
//BuildLocalizedApplicationBar();
}
protected override void OnManipulationStarted(ManipulationStartedEventArgs args)
{
BitmapImage bitmapImage = new BitmapImage(new Uri("/Images/123.png", UriKind.Relative));
bitmapImage.DecodePixelHeight = pictureheight;
bitmapImage.DecodePixelWidth = picturewidth;
Image imgBase = new Image();
imgBase.Source = bitmapImage;
imgBase.Stretch = Stretch.None;
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth / 2, bitmapImage.PixelHeight / 2);
writeableBitmap.Render(imgBase, null);
writeableBitmap.Invalidate();
imgUL.Source = writeableBitmap;
writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth / 2, bitmapImage.PixelHeight / 2);
TranslateTransform translate = new TranslateTransform();
translate.X = -bitmapImage.PixelWidth / 2;
writeableBitmap.Render(imgBase, translate);
writeableBitmap.Invalidate();
imgUR.Source = writeableBitmap;
writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth / 2, bitmapImage.PixelHeight / 2);
translate.X = 0;
translate.Y = -bitmapImage.PixelHeight / 2;
writeableBitmap.Render(imgBase, translate);
writeableBitmap.Invalidate();
imgLL.Source = writeableBitmap;
writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth / 2, bitmapImage.PixelHeight / 2);
translate.X = -bitmapImage.PixelWidth / 2;
writeableBitmap.Render(imgBase, translate);
writeableBitmap.Invalidate();
imgLR.Source = writeableBitmap;
args.Complete();
args.Handled = true;
base.OnManipulationStarted(args);
}
有人说是什么图片异步加载问题,求解释 WindowsPhone
[解决办法]
延迟加载引起的。
BitmapImage有三个设置图片数据源的方法。
1 构造函数;
2 UriSource属性;
3 SetSource(Stream)方法;
1和2会依据CreateOptions属性的值来决定何时加载图片
3是直接设置图片流,立马就加载出来了。
你的代码用时1 ,CreateOptions属性的默认值是DelayCreation,就是延迟,因为你的imgBase并未在UI呈现,所以BitmapImage就没有加载图片,导致图片宽高属性未0,后续几个WriteableBitmap也无法触发图片的加载。
如果不更改CreateOptions属性
在第一次创建WriteableBitmap 对象的时候如果
WriteableBitmap writeableBitmap = new WriteableBitmap(50, 50);随便写上一个宽高
writeableBitmap.Render(imgBase, null);执行下,也会触发BitmapImage去加载图片。