【发布时间】:2014-11-05 00:02:20
【问题描述】:
我想使用 Bing 今日图片作为我的应用锁屏图片的背景,但我无法让图片在 1080p 设备上按理想比例缩放。
这是一个 1080p 必应图片的示例:http://www.bing.com//az/hprichbg/rb/BeaverMeadow_EN-US12190942812_1920x1080.jpg。这是一张 1920 * 1080 的照片。
我所做的是裁剪它,使我使用的照片为 1080 * 1080 像素,然后创建一个 1080 * 1920 的新锁屏图像。这是代码:
public static void SaveToJpeg(Stream stream)
{
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isostream = iso.CreateFile("lockscreen.jpg"))
{
try
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Cropping image so that only 1080 out of the 1920 horizontal pixels are used.
wb = CropImage(wb, 1080, 1920, 1080, 1080);
// 1080 * 1920 are the phone's dimesions.
Extensions.SaveJpeg(wb, isostream, 1080, 1920, 0, 100);
isostream.Close();
}
catch( Exception e )
{
}
}
}
}
public static WriteableBitmap CropImage(WriteableBitmap source, int phoneWidth, int phoneHeight,
int width, int height)
{
// Based on the phone's width/height and image's width/height, will determine
// the correct x and y offsets.
int xOffset = 0, yOffset = 0;
if( phoneWidth >= source.PixelWidth )
{
xOffset = 0;
}
else
{
xOffset = source.PixelWidth - phoneWidth;
xOffset = xOffset / 2 + xOffset / 4;
}
if (phoneHeight >= height)
{
yOffset = 0;
}
else
{
yOffset = height - phoneHeight;
yOffset = yOffset / 2;
}
var sourceWidth = source.PixelWidth;
// Get the resultant image as WriteableBitmap with specified size
var result = new WriteableBitmap(width, height);
// Create the array of bytes
for (var x = 0; x <= height - 1; x++)
{
var sourceIndex = xOffset + (yOffset + x) * sourceWidth;
var destinationIndex = x * width;
Array.Copy(source.Pixels, sourceIndex, result.Pixels, destinationIndex, width);
}
return result;
}
不出所料,鉴于 Bing 图像的高度是 1080 像素(而不是 1920 像素),这就是锁定屏幕的样子:
而且,是的,创建锁定屏幕图像的自定义用户控件的网格背景图像被拉伸以填充:
<Grid.Background>
<ImageBrush
x:Name="Background"
Stretch="Fill"/>
</Grid.Background>
我需要做什么才能让 Bing 图像优雅地填满屏幕?也就是说,我不想不成比例地调整(像素化)原始图像的大小,以使其与 1080p 手机的尺寸相匹配。
更新:我为当天的 Bing 图片找到了一张 1080 x 1920 的替代照片(即具有 1080p 手机锁定屏幕的精确尺寸):http://www.bing.com//az/hprichbg/rb/BeaverMeadow_EN-US12190942812_1080x1920.jpg。
但是使用它似乎并不能解决根本问题(注意:我没有从这张图片中裁剪任何东西,而是按原样使用这张图片,因为尺寸是完美的)。见下文:
【问题讨论】:
标签: windows-phone-8 windows-phone scaling lockscreen image-scaling