WPF call graphic draw functions via bitmap converting to bitmapimage
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using static System.Net.Mime.MediaTypeNames; namespace WpfApp78 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { Render(); //Render2(); } private BitmapImage GenerateBMIFromBitmap(Bitmap bmp) { using (MemoryStream ms = new MemoryStream()) { bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; var bmi = new BitmapImage(); bmi.BeginInit(); bmi.StreamSource = ms; bmi.CacheOption = BitmapCacheOption.OnLoad; bmi.EndInit(); if (bmi.CanFreeze) { bmi.Freeze(); } return bmi; } } private void Render2() { using (var bmp = new Bitmap((int)this.ActualWidth, (int)this.ActualHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.Clear(System.Drawing.Color.Navy); System.Drawing.Image image = System.Drawing.Image.FromFile(@"../../Images/1.jpg"); g.DrawImage(image, new System.Drawing.Rectangle(0, 0, (int)this.ActualWidth, (int)this.ActualHeight)); this.Background = new ImageBrush(GenerateBMIFromBitmap(bmp)); } } } Random rand= new Random(); private void Render() { using (var bmp = new Bitmap((int)this.ActualWidth, (int)this.ActualHeight)) using (var gfx = Graphics.FromImage(bmp)) using (var pen = new System.Drawing.Pen(System.Drawing.Color.White)) { // draw one thousand random white lines on a dark blue background gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; gfx.Clear(System.Drawing.Color.Navy); for (int i = 0; i < 1000; i++) { var pt1 = new System.Drawing.Point(rand.Next(bmp.Width), rand.Next(bmp.Height)); var pt2 = new System.Drawing.Point(rand.Next(bmp.Width), rand.Next(bmp.Height)); gfx.DrawLine(pen, pt1, pt2); } this.Background=new ImageBrush(GenerateBMIFromBitmap(bmp)); } } } }