如何正确保存UIControl与不透明度WriteableBitmap?

时间:2014-03-04 12:38:14

标签: c# silverlight windows-phone

我制作了一组具有不同不透明度值的矩形,并将这些矩形添加到WindowsPhone中的Grid:

var grid=new Grid();
grid.Width = grid.Height = 200;
var rectanglesCount=55;
var rectangleSizeStep = grid.Height / rectanglesCount;
var opacityStep = 1.0 / rectanglesCount
var rectangleSize = grid.Height;
var opacity = 0.0;
for (int i = 0; i <= rectanglesCount; i++)
{
Rectangle rect = new Rectangle();
rect.Height = rect.Width = rectangleSize;
rect.VerticalAlignment = VerticalAlignment.Center;
rect.HorizontalAlignment = HorizontalAlignment.Center;
rect.Fill = new SolidColorBrush(Colors.Yellow);
rect.Opacity = opacity;
opacity += opacityStep;
rectangleSize -= rectangleSizeStep;
grid.Children.Add(rect);
}

我可以在网格中看到以下图片: enter image description here

尝试将此组矩形保存到WriteableBitmap并显示为Image:

var img=new Image();
var wrBit = new WriteableBitmap(grid, null);
img.Source=wrBit;

我看到图片: enter image description here

上边缘和左边缘的不透明度会发生什么? 如何正确保存矩形组?

1 个答案:

答案 0 :(得分:1)

需要使用Canvas代替网格控件来处理矩形组:

var canvas=new Canvas();
canvas.Width = canvas.Height = 200;
var rectanglesCount=55;
var rectangleSizeStep = canvas.Height / rectanglesCount;
var opacityStep = 1.0 / rectanglesCount
var rectangleSize = canvas.Height;
var opacity = 0.0;
var rectMargin = 0.0;
for (int i = 0; i <= rectanglesCount; i++)
{
Rectangle rect = new Rectangle();
rect.Height = rect.Width = rectangleSize;
rect.Margin=new Thickness(rectMargin,rectMargin,0,0);
rectMargin += rectangleSizeStep/2;
rect.Fill = new SolidColorBrush(Colors.Yellow);
rect.Opacity = opacity;
opacity += opacityStep;
rectangleSize -= rectangleSizeStep;
canvas.Children.Add(rect);
}

并将Canvas另存为WriteableBitmap:

var img=new Image();
var wrBit = new WriteableBitmap(canvas, null);
img.Source=wrBit;

问题解决了!