将字符串转换为图像(任何格式的位图或ico最喜欢)wpf c#
本文关键字:ico 喜欢 wpf 位图 转换 字符串 图像 格式 任何 | 更新日期: 2023-09-27 18:20:46
我有几个数字想显示在托盘图标中。。。为此,我需要将这些数字转换为图标或任何位图图像。。。。需要帮助的是他们在wpf c#中的任何类或属性。任何方法。。我尝试的方法不起作用。。。
Font fnt = new Font("Tahoma", 8 );
fntheight += fnt.Height;
int maxheight = 0;
if (state == true)
maxheight = height + fntheight + fntheight;
else
maxheight = height + fntheight;
Graphics grf = Graphics.FromImage(myimg);
Image newimg = new System.Drawing.Bitmap(width, maxheight);
Graphics newgrf = Graphics.FromImage(newimg);
newgrf.FillRectangle(Brushes.White, 0, 0, width, height);
但该代码在当前的wpf c#.net 4+中不起作用
首先需要添加:
Using System.Drawing.Imaging;
using System.Windows.Interop;
将文本转换为位图:
public Bitmap TextToBitmap(string txt, string fontname, int fontsize, Color bgcolor, Color fcolor, int Width, int Height)
{
Bitmap bmp = new Bitmap(Width, Height);
using (Graphics graphics = Graphics.FromImage(bmp))
{
Font font = new Font(fontname, fontsize);
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
graphics.Flush();
font.Dispose();
graphics.Dispose();
}
return bmp;
}
将位图转换为位图图像:
public BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bitImage = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
bitImage.BeginInit();
bitImage.StreamSource = new MemoryStream(memoryStream.ToArray());
bitImage.EndInit();
memoryStream.Close();
return bitImage;
}
将转换后的BitmapImage设置为使用System.Windows.Media.Brush
的元素
public void SetBitmapImage()
{
System.Drawing.Bitmap bmp = TextToBitmap(*whatever goes here);
*Element.Background = new ImageBrush(BitmapToBitmapImage(bmp));
}
将转换后的BitmapImage设置为使用System.Windows.Media.Image
的元素
public void SetBitmapImage()
{
System.Drawing.Bitmap bmp = TextToBitmap(*whatever goes here);
*Element.Source = BitmapToBitmapImage(bmp);
}
@MikMagic您可以通过BitmapSource对象将System.Drawing.Bitmap转换为System.Windows.Media.Image。
请参阅此代码项目的文章和MSDN文档。