动态裁剪BitmapImage对象

roh*_*its 4 c# bitmapimage silverlight-4.0

我有一个BitmapImage对象,其中包含600 X 400维度的图像.现在从我的C#代码后面,我需要创建两个新的BitmapImage对象,比如每个尺寸为600 X 200的objA和objB,使得objA包含上半部分裁剪图像,objB包含原始图像的下半部分裁剪图像.

Tho*_*que 5

BitmapSource topHalf = new CroppedBitmap(sourceBitmap, topRect);
BitmapSource bottomHalf = new CroppedBitmap(sourceBitmap, bottomRect);
Run Code Online (Sandbox Code Playgroud)

结果不是a BitmapImage,但它仍然是有效的ImageSource,如果你只是想显示它应该没问题.


编辑:实际上有一种方法可以做到这一点,但它非常难看......你需要Image用原始图像创建一个控件,并使用该WriteableBitmap.Render方法来渲染它.

Image imageControl = new Image();
imageControl.Source = originalImage;

// Required because the Image control is not part of the visual tree (see doc)
Size size = new Size(originalImage.PixelWidth, originalImage.PixelHeight);
imageControl.Measure(size);
Rect rect = new Rect(new Point(0, 0), size);
imageControl.Arrange(ref rect);

WriteableBitmap topHalf = new WriteableBitmap(originalImage.PixelWidth, originalImage.PixelHeight / 2);
WriteableBitmap bottomHalf = new WriteableBitmap(originalImage.PixelWidth, originalImage.PixelHeight / 2);

Transform transform = new TranslateTransform();
topHalf.Render(originalImage, transform);
transform.Y = originalImage.PixelHeight / 2;
bottomHalf.Render(originalImage, transform);
Run Code Online (Sandbox Code Playgroud)

免责声明:此代码完全未经测试;)