2011-02-28 42 views
1

我有一個問題system.drawing和WPF之間的互操作問題。爲了簡化這個問題,我構建了一個例子來說明問題。我使用System.Drawing繪製,然後使用CreateBitmapSourceFromHBitmap將結果複製到System.Windows.Controls.Image。不知何故,你可以在屏幕截圖中看到alpha信息丟失。System.Drawing和WPF互操作 - CreateBitmapSourceFromHBitmap

在透明位圖上繪製黑色文本,然後將其複製到透明的圖像組件。父網格本身具有黑色背景。我猜想,結果是一個完全黑色的圖像,但它不是,文本似乎在進行抗鋸齒時使用白色作爲背景進行繪製。

Link to Screenshot

下面是MainWindow.xaml代碼:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid Name="grid" Background="Black"> 
     <Image Name="image" Stretch="Fill" Loaded="image_Loaded"></Image> 
    </Grid> 
</Window> 

而對於MainWindow.xaml.cs代碼:

using System; 
using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Drawing.Text; 
using System.Windows; 

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void image_Loaded(object sender, RoutedEventArgs e) 
     { 
      //use system drawing to draw text 
      Bitmap bmp = new Bitmap ((Int32) grid.ActualWidth, (Int32) grid.ActualHeight); 
      Graphics graphics = Graphics.FromImage (bmp); 

      var brush = new SolidBrush(Color.FromArgb(255, 0, 0, 0)); 
      var font = new Font(System.Drawing.FontFamily.GenericSansSerif, 30.0f, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel); 

      graphics.Clear(Color.Transparent); 
      graphics.SmoothingMode = SmoothingMode.HighQuality; 
      graphics.CompositingMode = CompositingMode.SourceOver; 
      graphics.CompositingQuality = CompositingQuality.HighQuality; 

      //draw text 
      graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; 
      graphics.TextContrast = 5; 
      graphics.DrawString("My Text", font, brush, 10, 10); 

      //try saving 
      bmp.Save("E:\\temp.png", System.Drawing.Imaging.ImageFormat.Png); 

      //back to wpf image control 
      image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap (bmp.GetHbitmap (), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromWidthAndHeight ((Int32) grid.ActualWidth, (Int32) grid.ActualHeight)); 
     } 
    } 
} 

有誰經歷過這一點?我怎樣纔能有一個平滑的抗鋸齒效果,它不會與白色相乘?

回答

0

不是最迷人的解決方案,但我可以讓它正常工作的唯一方法是通過與保存()函數保存位圖,然後對其進行解碼,並加載它作爲一個的BitmapSource:

 bmp.Save("E:\\temp.png", System.Drawing.Imaging.ImageFormat.Png); 
    //A neater way to free up the file! 
    bmp.Dispose(); 
    bmp = null; 
    //Load up the image. 
    BitmapFrame frm = new BitmapFrame(new Uri("E:\\temp.png")); 
    image.Source = frm as BitmapSource; 

現在,這不是最好的解決方案,但這是我所能遇到的。

+0

你不需要這個骯髒的黑客來釋放文件...保存完成後關閉文件。無論如何,你總是可以調用bmp.Dispose明確地 – 2011-05-02 10:13:24

+0

是的,我想是的 - 當時沒有想到。我會修復我的答案,並將其排除以避免混淆。 – epxp 2011-05-02 17:02:07