by weiloonhow » Aug 24, 2017 02:18
Hi MartynasV,
Thank you for the reply.
I have managed to find out the root cause after spending half a day.
The position of the subject rectangle was not correct is due to the TranslateTransform and ScaleTransform.
As I am using WPF instead of Winforms, I need to perform a TranslateTransform and ScaleTransform after the NImage was drawn. Follow by a TranslateTransform and ScaleTransform again after the Subject Rectangle was drawn.
I am not too sure if this is really the correct approach.
Would appreciate if any WPF expert could advise me if I am wrong in this.
Below is my code, Thank you so much.
private void PaintScenes(DrawingContext dc)
{
for (int i = 0; i < _sceneData.Count; i++)
{
SceneData data = _sceneData[i];
Rect rect = GetQuadrant(i, _sceneData.Count);
double scalex = 1, scaley = 1;
if (data.Width != 0 && data.Height != 0 && ActualWidth != 0 && ActualHeight != 0)
{
scalex = (double)ActualWidth / data.Width / (ActualWidth / rect.Width);
scaley = (double)ActualHeight / data.Height / (ActualHeight / rect.Height);
}
double scale = Math.Min(scalex, scaley);
double dx = Math.Round((rect.Width - data.Width * scale) / 2.0);
double dy = Math.Round((rect.Height - data.Height * scale) / 2.0);
TranslateTransform translateTransform = new TranslateTransform((float)(rect.X + dx), (float)(rect.Y + dy));
ScaleTransform scaleTransform = new ScaleTransform((float)scale, (float)scale);
if (data.Image != null)
{
if (data.Bmp == null)
data.Bmp = data.Image.ToBitmap();
var imageRect = new Rect
{
X = 0,
Y = 0,
Width = data.Width,
Height = data.Height
};
using (var bitmap = new System.Drawing.Bitmap(data.Bmp))
{
IntPtr hBitmap = bitmap.GetHbitmap();
try
{
var bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
bitmap.Dispose();
dc.DrawImage(bitmapSource, rect);
}
finally
{
DeleteObject(hBitmap);
}
}
dc.PushTransform(scaleTransform);
dc.PushTransform(translateTransform);
}
PaintScene(dc, data);
data.Scene.CleanSceneInfo();
dc.PushTransform(scaleTransform);
dc.PushTransform(translateTransform);
}
}