【问题标题】:Transparency problems when adding an overlay to an icon向图标添加叠加层时出现透明度问题
【发布时间】:2011-10-27 20:42:58
【问题描述】:

我有一个.ico 文件和一个.png 文件,该文件具有我想应用于图标的叠加层。我在这方面非常缺乏经验,所以设法从互联网上获取一些代码,直到我有一些几乎可以工作的东西。

问题是透明度丢失并被白色替换。

另外,我认为颜色范围减少了。我添加了一些调试代码(注释掉)以在 2 个阶段保存图标。当我在 VS 2010 的第一阶段编辑它时,调色板有 16 种颜色,stage1.ico 有更多。

似乎是Icon.FromHandle 导致了问题。下面的函数接受两个 ImageSource 参数。第一个来自.ico 文件,第二个来自.png 文件(叠加)。

我应该怎么做?

功能-

private static Icon Render(ImageSource baseImage, ImageSource overlay)
{
  int iconSize = 32;

  RenderTargetBitmap renderBitmap
    = new RenderTargetBitmap(iconSize,
    iconSize,
    96, 96,
    PixelFormats.Pbgra32);

  DrawingVisual visual = new DrawingVisual();
  using (DrawingContext context = visual.RenderOpen())
  {
    context.DrawImage(baseImage, new System.Windows.Rect(0, 0, iconSize, iconSize));
    context.DrawImage(overlay, new System.Windows.Rect(0, 0, iconSize, iconSize));
    context.Close();
    renderBitmap.Render(visual);
  }
  BmpBitmapEncoder encoder = new BmpBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
  MemoryStream stream = new MemoryStream();
  encoder.Save(stream); 

  Bitmap bmp = new Bitmap(stream);
  //bmp.Save("c:\\tmp\\stage1.ico"); // save what we have here
  IntPtr Hicon = bmp.GetHicon();
  Icon icon = Icon.FromHandle(Hicon);
  // Looking at stage2.ico gives a different version to stage1.ico
  //using (var fs = new FileStream("c:\\tmp\\stage2.ico", FileMode.Create, FileAccess.Write, FileShare.Delete))
  //{
    //icon.Save(fs);
  //}
  return icon;
}

【问题讨论】:

  • 使用此图标的部分是 WinForms,尽管我稍后会调用 WPF 窗口。 WinForms 部分在系统托盘中显示一个图标 - 正是这个图标出现了问题。谢谢。
  • GetHicon() 是问题所在,它使用了一种非常原始的算法。它使用只有 16 种原色的调色板。除非图像非常简单,否则结果总是令人失望。这是一个难题,我不知道任何完美的解决方案。
  • 好吧,我想我的选择是让做图标的人应用叠加层,而不是尝试在代码中做。感谢您的回复。

标签: c# .net winforms icons overlay


【解决方案1】:

我能够使用下面的代码动态创建一个透明的图标,用作覆盖图标。对于我的程序,我想要一个显示有多少新消息排队的数字。请原谅VB...

Private _counter As Integer = 0

Public Sub NewMessageIncrementOverlay()
  _counter += 1
  Dim displayVal = If(_counter > 9, "+", _counter.ToString)

  Dim bitm As Bitmap = New Bitmap(40, 40,
                         System.Drawing.Imaging.PixelFormat.Format32bppArgb)
  Dim g As Graphics = Graphics.FromImage(bitm)
  g.FillRectangle(System.Drawing.Brushes.Transparent, 0, 0, 40, 40)
  g.FillPie(System.Drawing.Brushes.Red, 0, 0, 40, 40, 0, 360)
  g.DrawString(displayVal, New Font("Consolas", 30, FontStyle.Bold),
               System.Drawing.Brushes.White, New PointF(3, -5))

  If TaskbarManager.IsPlatformSupported Then
    Dim icon As Icon = icon.FromHandle(bitm.GetHicon)
    TaskbarManager.Instance.SetOverlayIcon(icon, displayVal)
  End If
End Sub

【讨论】:

    猜你喜欢
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2012-06-28
    • 2020-01-07
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多