You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在透明Bitmap上绘制带透明度的红色字符串?解决黑红混色问题

正确实现透明Bitmap上绘制半透明红色文本的VB.NET方案

问题原因

默认创建的Bitmap背景为黑色(不透明),当你绘制带透明度的红色文本时,文本颜色会与黑色背景混合,最终呈现黑红混合的效果,而非预期的半透红色。

正确实现步骤

  • 创建Bitmap时明确指定支持Alpha通道的像素格式Format32bppArgb
  • 用Graphics.Clear(Color.Transparent)将Bitmap背景清空为透明
  • 使用Using语句自动释放资源,避免内存泄漏
  • 可选:设置Graphics的文本渲染属性优化显示效果

完整代码

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Invalidate()
    End Sub

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        ' 创建支持Alpha通道的透明Bitmap
        Using Img As New Bitmap(300, 300, Imaging.PixelFormat.Format32bppArgb)
            Using G As Graphics = Graphics.FromImage(Img)
                ' 将Bitmap背景设为透明
                G.Clear(Color.Transparent)
                ' 优化文本渲染质量,可选
                G.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit

                ' 绘制带透明度的红色文本(Alpha值50,红色255)
                Dim semiTransRedBrush As New SolidBrush(Color.FromArgb(50, 255, 0, 0))
                G.DrawString("SIMPLE TEST!", New Font("Arial", 50), semiTransRedBrush, New Point(0, 0))
                semiTransRedBrush.Dispose()
            End Using
            ' 将透明Bitmap绘制到窗体
            e.Graphics.DrawImage(Img, New Point(0, 0))
        End Using
    End Sub
End Class

补充说明

  • Color.FromArgb(50, 255, 0, 0)的第一个参数是Alpha值(0为完全透明,255为完全不透明),调整该值可控制文本透明度
  • Using语句会自动释放Bitmap和Graphics对象,无需手动调用Dispose(),更安全高效
  • 设置TextRenderingHint可让文本边缘更平滑,提升显示效果

内容的提问来源于stack exchange,提问作者czxinc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:25:43