1
我有一个问题system.drawing和WPF之间的互操作问题。为了简化这个问题,我构建了一个例子来说明问题。我使用System.Drawing绘制,然后使用CreateBitmapSourceFromHBitmap将结果复制到System.Windows.Controls.Image。不知何故,你可以在屏幕截图中看到alpha信息丢失。System.Drawing和WPF互操作 - CreateBitmapSourceFromHBitmap
在透明位图上绘制黑色文本,然后将其复制到透明的图像组件。父网格本身具有黑色背景。我猜想,结果是一个完全黑色的图像,但它不是,文本似乎在进行抗锯齿时使用白色作为背景进行绘制。
下面是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));
}
}
}
有谁经历过这一点?我怎样才能有一个平滑的抗锯齿效果,它不会与白色相乘?
你不需要这个肮脏的黑客来释放文件...保存完成后关闭文件。无论如何,你总是可以调用bmp.Dispose明确地 – 2011-05-02 10:13:24
是的,我想是的 - 当时没有想到。我会修复我的答案,并将其排除以避免混淆。 – epxp 2011-05-02 17:02:07