I'm new in WPF.

I have implemented code in mfc which load the bitmap and draw it some portion on window now want to port the similar functionality in WPF.

I want to draw bitmap on my WPF window and do some operation. window will not have min, max, close button.

below is my mfc code.

LRESULT Mywindow::OnPaint(UINT, WPARAM, LPARAM, BOOL&)
        {
            CPaintDC dc(this);
        CDC cdc;
        HDC hdc = dc.GetSafeHdc();
        cdc.Attach(hdc);
        paintBitmapOnWindow(&cdc);
        }

    void Mywindow::paintBitmapOnWindow(CDC* pCdc)
    {
         HBITMAP backgroundBitmap;
        backgroundBitmap = (HBITMAP)::LoadImage(0, _T("C:\\temp.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        CDC cdcCompatible;
        cdcCompatible.CreateCompatibleDC(pCdc);
        cdcCompatible.SelectObject(backgroundBitmap);

        CRect clientRect;
        GetClientRect(clientRect);

        int clientHalfWidth = 800 / 2;
        CRect clientLeft;
        CRect imageLeft;
        BITMAP bm;
        ::GetObject(backgroundBitmap, sizeof(BITMAP), (PSTR)&bm);

        clientLeft.SetRect(clientRect.left, clientRect.top, clientRect.left + clientHalfWidth, clientRect.bottom);

        int bitmapHalfWidth = bm.bmWidth / 2;
        int bitmapLeftOffset = bitmapHalfWidth - 0;

        imageLeft.SetRect(bitmapLeftOffset - clientLeft.Width(), 0, bitmapLeftOffset, bm.bmHeight);

        pCdc->StretchBlt(clientLeft.left, clientLeft.top, clientLeft.Width(), clientLeft.Height(), &cdcCompatible,
            imageLeft.left, imageLeft.top, imageLeft.Width(), imageLeft.Height(), SRCCOPY);
        cdcCompatible.DeleteDC();
    }

what are the similar function/class which i can use to convert it into WPF?

有帮助吗?

解决方案

If you are looking to blit the bitmap directly to the window, and you wish to directly control the rendering you may simply override the OnRender function. However there is on catch (noted in the comments of the code)...

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Background = Brushes.Transparent;  // <-- necessary  (strange bug)
        // Charles Petzold writes about this at the following link:
        // http://social.msdn.microsoft.com/Forums/vstudio/en-US/750e91c2-c370-4f0a-b18e-892afd99bd9b/drawing-in-onrender-beginnerquestion?forum=wpf
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);
        BitmapSource bitmapSource = new BitmapImage(new Uri("C:\\Temp.png", UriKind.Absolute));
        CroppedBitmap croppedBitmap = new CroppedBitmap(bitmapSource, new Int32Rect(20, 20, 100, 100));
        drawingContext.DrawImage(croppedBitmap, new Rect(0.0d, 0.0d, this.RenderSize.Width / 2.0d, this.RenderSize.Height));
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top