clamp
clamp

Reputation: 34036

Loading and displaying JPG image by code

I am trying to load and display an image using WPF, but it does not work.

public partial class MainWindow : Window
{
    BitmapImage imgsrc;

    public MainWindow()
    {
        InitializeComponent();

        imgsrc = new BitmapImage();
        imgsrc.BeginInit();
        imgsrc.UriSource = new Uri("c.jpg", UriKind.Relative);
        imgsrc.EndInit();
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
         base.OnRender(drawingContext);
         drawingContext.DrawImage(imgsrc, new Rect(10, 10, 100, 100));
    }
}

the c.jpg file is in the project and marked for copy to output.

the applications runs without errors and shows a white empty window

Upvotes: 1

Views: 188

Answers (2)

Andreas
Andreas

Reputation: 112

The OnRender(...) method on classes inheriting from Window does not work how you excpect. You might try something like this:

In your XAML

<Window x:Class="WpfTestApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:own="clr-namespace:WpfTestApplication"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <own:MyRect />
</Grid>
</Window>

And here your element that displays your image (replace the rectangle with your image logic)

public class MyRect : Panel
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        SolidColorBrush mySolidColorBrush = new SolidColorBrush();
        mySolidColorBrush.Color = Colors.LimeGreen;
        Pen myPen = new Pen(Brushes.Blue, 10);
        Rect myRect = new Rect(0, 0, 500, 500);
        drawingContext.DrawRectangle(mySolidColorBrush, myPen, myRect);
    }
}

Upvotes: 0

GazTheDestroyer
GazTheDestroyer

Reputation: 21261

This is a known issue with overriding OnRender() on a Window.

Don't derive from Window, use FrameworkElement instead, or if you must use Window try setting the background to transparent.

Upvotes: 2

Related Questions