c# - 向图标添加叠加层时出现透明度问题

标签 c# .net winforms icons overlay

我有一个 .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;
}

最佳答案

我能够使用以下代码动态创建一个具有透明度的图标,用作覆盖图标。对于我的程序,我想要一个数字来显示有多少新消息排队。请原谅 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

关于c# - 向图标添加叠加层时出现透明度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075249/

相关文章:

c# - 关键事件 : ProcessCmdKey

c# - 在 LINQ 中使用数组查询的位置

c# - 文本框只允许小数点后两位数?

c# - 在 ASP.NET MVC 中使用破折号进行路由

c# - 将 XML 反序列化为对象时缺少子节点

c# - 在应用程序中导航已激活的 Windows Phone 7(逻辑删除)

c# - 我的文本框上没有显示水平滚动条

c# - 如何替换 TreeView 中的 TreeNode?

c# - Mono Develop Microsoft Authentication for Microsoft Analysis 服务器

c# - 在 gridview 中动态填充列标题