首页 > 解决方案 > 具有完整 Alpha 通道支持的 WinForms 位图

问题描述

当我在位图图形上绘制具有半透明像素的图像,然后在屏幕上绘制位图时,这些像素变为黑色。

同时,图像周围的纯透明像素保持透明。

谁知道如何解决这个问题?

这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Drawing.Drawing2D;

namespace SimpleTest
{
  public partial class Form12_BitmapAlpha : Form
  {
    public Form12_BitmapAlpha()
    {
      InitializeComponent();
    }

    private void Panel1_Paint(object sender, PaintEventArgs e)
    {
      //Back
      e.Graphics.FillRectangle(new SolidBrush(Color.Coral), new Rectangle(5, 5, 25, 85));

      // 1
      RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(10, 10), RadioButtonState.CheckedNormal);

      //2
      Size cbSize = RadioButtonRenderer.GetGlyphSize(e.Graphics, RadioButtonState.CheckedNormal);
      Bitmap cbBitmap = new Bitmap(cbSize.Width, cbSize.Height);

      using (Graphics offscreen = Graphics.FromImage(cbBitmap))
      {
        //offscreen.CompositingMode = CompositingMode.SourceCopy; //doesn't work
        //offscreen.Clear(Color.Transparent); //it doesn't help
        RadioButtonRenderer.DrawRadioButton(offscreen, new Point(0, 0), RadioButtonState.CheckedNormal);
      }

      e.Graphics.DrawImage(cbBitmap, new Point(10, 40));

      //3
      RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(10, 70), RadioButtonState.CheckedNormal);
      Bitmap cbBitmap1 = new Bitmap(20, 20);

      using (Graphics offscreen = Graphics.FromImage(cbBitmap1))
      {
        offscreen.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.Red)), new Rectangle(2, 2, 16, 16));
      }

      e.Graphics.DrawImage(cbBitmap1, new Point(0, 65));
    }
  }
}

在代码的第一部分,(在 //1 下)我直接在 Panel 的 Graphics 上绘制,您可以看到 RadioButton 的边缘以半透明颜色绘制。

在代码的第二部分(在 //2 下),我绘制了同样的东西,但是通过一个 Bitmap 对象。这里的边框被画成黑色。

而在第三部分(在 //3 下),我在一个 Bitmap 上绘制了一个半透明的正方形,然后在屏幕上绘制这个 Bitmap 以显示 Bitmap 支持半透明区域。

和结果

在此处输入图像描述

标签: c#winformsbitmapalpha-transparency

解决方案


推荐阅读