合并半透明PNG时控制图像位置大小适配Zoom模式PictureBox
问题根因
你遇到的裁切、不居中问题是因为GDI+的Graphics默认会根据图像的DPI参数自动调整绘制尺寸,且默认单位不是像素,导致源图绘制时被放大超出了目标Bitmap的边界,最终展示在SizeMode=Zoom的pictureBox1中就出现了裁切偏移的问题。
修正后的可运行代码
private void button2_Click(object sender, EventArgs e) { // 用using自动释放源图像资源,避免内存泄漏 using (var source1 = (Bitmap)Image.FromFile(Path.Combine(imgPath, "myImg1.png"))) using (var source2 = (Bitmap)Image.FromFile(Path.Combine(imgPath, "myImg2.png"))) { // 创建和源图尺寸一致的目标画布,同时匹配源图的DPI设置 var target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb); target.SetResolution(source1.HorizontalResolution, source1.VerticalResolution); using (var graphics = Graphics.FromImage(target)) { graphics.CompositingMode = CompositingMode.SourceOver; // 显式指定绘制的目标区域、源区域,强制单位为像素,避免GDI+自动缩放 graphics.DrawImage(source1, new Rectangle(0, 0, source1.Width, source1.Height), 0, 0, source1.Width, source1.Height, GraphicsUnit.Pixel); graphics.DrawImage(source2, new Rectangle(0, 0, source2.Width, source2.Height), 0, 0, source2.Width, source2.Height, GraphicsUnit.Pixel); } // 释放旧图像资源后再赋值新图像 pictureBox1.Image?.Dispose(); pictureBox1.Image = target; } }
自定义绘制位置/大小的方法
如果需要调整两张图的绘制位置、缩放比例,直接修改DrawImage方法的第一个参数(目标矩形)即可:
- 水平居中:目标X坐标设为
(target.Width - 绘制内容宽度) / 2 - 垂直居中:目标Y坐标设为
(target.Height - 绘制内容高度) / 2 - 修改目标矩形的宽高即可实现绘制时的缩放,且不会改变目标画布的总尺寸,保证
pictureBox的Zoom模式能正常居中展示完整内容。
内容的提问来源于stack exchange,提问作者user16653829
相关产品推荐
相关产品推荐

