【发布时间】:2017-09-09 09:57:01
【问题描述】:
我目前正在使用 GDI+ 用 C# 开发游戏引擎。目前,我正在尝试通过实现一种更快的方式将一个位图复制到另一个位图来使图形引擎更快地渲染位图。
我有一个名为CopyBitmap 的方法,它接收您希望从中复制的位图、您希望复制到的位图、目标矩形(您希望放置到复制图像的位置和大小) 和一个源矩形(这是您要复制的图像部分)。
但是,我不知道如何设置复制图像的位置和大小。
我该怎么做呢?
这是我目前的代码:
/// <summary>
/// Copies the <see cref="BitmapData"/> from one <see cref="Bitmap"/> to another.
/// </summary>
/// <param name="from">The <see cref="Bitmap"/> you wish to copy from.</param>
/// <param name="to">The <see cref="Bitmap"/> you wish to copy to.</param>
/// <param name="destRect">The location and size of the copied image.</param>
/// <param name="srcRect">The portion of the image you wish to copy.</param>
public static void CopyBitmap(Bitmap from, Bitmap to, Rectangle destRect, Rectangle srcRect)
{
// The bitmap we're copying from needs to know the portion of the bitmap we wish to copy
// so lets pass it the src rect, it is also read only.
BitmapData fromData = from.LockBits(srcRect, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
// The bitmap we're copying to needs to know where the copied bitmap should be placed, and also how big it is
// so lets pass it the dest rect, it is also write only
BitmapData toData = to.LockBits(destRect, ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
// Declare an array to hold the bytes of data we're copying from
int bytes = Math.Abs(fromData.Stride) * from.Height;
// convert it to bytes
byte[] rgbValues = new byte[bytes];
// I imaginge here is where I should set the position and size of the image I wish to copy to it's destRect
// Copy the values to the bitmap we're copying to
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, toData.Scan0, bytes);
// unlock them both
from.UnlockBits(fromData);
to.UnlockBits(toData);
}
我认为值得一提的是,我不希望使用 graphics.DrawImage 方法,因为这就是我首先创建该方法的原因。
【问题讨论】:
-
旁注,您需要检查
destRect和srcRect是否正确位于各自图像的范围内 -
谢谢,我现在就做。很明显,id 用一个简单的 Rectangle.IntersectsWith 校验来做到这一点?
-
您可以按照自己的意愿进行操作,但是应该可以。