如何合并两个System.Windows.Controls.Image对象?
WPF 合并 System.Windows.Controls.Image 对象的实现方法
WPF 的 System.Windows.Controls.Image 是 UI 控件,无法像 System.Drawing.Bitmap 那样直接进行像素级合并。我们可以通过渲染组合后的UI容器生成新图像源,再赋值给目标Image控件,同时保持其控件类型不变。
实现思路
- 创建一个容器(如Canvas),将目标图像和待合并图像按指定位置放入容器;
- 使用
RenderTargetBitmap将容器渲染为BitmapSource; - 将生成的
BitmapSource赋值给目标Image控件的Source属性,完成合并。
扩展方法实现(模拟你需要的Merge方法)
可以封装一个扩展方法,方便直接调用:
using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; public static class ImageExtensions { public static void Merge(this Image targetImage, Image sourceImage, Rect position) { // 验证参数有效性 if (targetImage?.Source == null || sourceImage?.Source == null) return; // 创建Canvas作为合并容器 var mergeContainer = new Canvas(); // 添加目标图像到容器 var targetVisual = new Image { Source = targetImage.Source, Width = targetImage.ActualWidth > 0 ? targetImage.ActualWidth : targetImage.Source.Width, Height = targetImage.ActualHeight > 0 ? targetImage.ActualHeight : targetImage.Source.Height }; Canvas.SetLeft(targetVisual, 0); Canvas.SetTop(targetVisual, 0); mergeContainer.Children.Add(targetVisual); // 添加待合并图像,设置指定位置和尺寸 var sourceVisual = new Image { Source = sourceImage.Source, Width = position.Width, Height = position.Height }; Canvas.SetLeft(sourceVisual, position.X); Canvas.SetTop(sourceVisual, position.Y); mergeContainer.Children.Add(sourceVisual); // 确定容器的最终尺寸 mergeContainer.Width = Math.Max(targetVisual.Width, position.X + position.Width); mergeContainer.Height = Math.Max(targetVisual.Height, position.Y + position.Height); // 渲染容器为BitmapSource var renderBitmap = new RenderTargetBitmap( (int)mergeContainer.Width, (int)mergeContainer.Height, 96, 96, // 屏幕DPI PixelFormats.Pbgra32); // 支持透明通道 renderBitmap.Render(mergeContainer); // 更新目标Image的源和尺寸 targetImage.Source = renderBitmap; targetImage.Width = mergeContainer.Width; targetImage.Height = mergeContainer.Height; } }
使用方式
直接调用扩展方法即可:
// 假设已完成image1和image2的初始化与加载 image1.Merge(image2, new Rect(0, 0, 15, 15));
注意事项
- 确保调用方法时,两个Image控件已完成布局(比如在
Loaded事件后调用),否则ActualWidth/ActualHeight可能为0,此时可以直接使用Source的宽高替代; - 若需保留图像透明效果,务必使用
PixelFormats.Pbgra32格式; - 合并后目标Image的
Source会替换为新生成的BitmapSource,但控件类型仍为System.Windows.Controls.Image,满足你的需求。
内容的提问来源于stack exchange,提问作者user613832
相关产品推荐
相关产品推荐

