65.9K
CodeProject 正在变化。 阅读更多。
Home

制作用于纹理画笔的透明位图或混合两个位图

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.86/5 (9投票s)

2007年1月11日

CPOL

1分钟阅读

viewsIcon

37956

少量代码可以在您需要时模拟透明度,而无需管理 Alpha 通道。

引言

我搜索了很长时间,寻找一种使用 .NET 代码轻松合并两个位图的方法。我总是被引导回 GDI bitblt,这对于 .NET 风格的图像来说不太友好。或者管理 Alpha 通道。我想我错过了一些东西……?最终,我设计了一种简单的方法,可以为任何 .NET 位图应用可变的透明度。这实际上并没有以真正的意义上在两个位图之间混合颜色,而是设置位图 A 中的透明度百分比,当用作应用于位图 B 的纹理画笔时,效果非常好。

指定正确的矩形将允许典型的叠加。此示例在您查看屏幕 2 时平铺叠加。这是使用此画笔的代码,此处未显示。此代码将透明度表示为白色。此代码允许您在不管理 Alpha 通道的情况下混合位图。

令人困惑的是,Windows 颜色集拥有 1600 万种颜色,却没有保留一种透明颜色。Bitmap.MakeTransparent 允许您分配透明颜色。此代码将以一种很好的混合方式分配透明颜色,使其正常工作。

此代码简单且运行速度快。只需将此代码中的位图用作带有 bitmap.maketransparency(system.drawing.color.white) 的纹理画笔即可。

Public Sub SetAlphaVary(ByRef abm As Image)
' This code is from DesignLab(C)2007 author Dominic J. Melfi
' It may be used freely as long as the above line is included
=====================================================

' abm is passed as the "Source Image"

' size of source 

Dim r1 As RectangleF
r1.X = 0
r1.Y = 0
r1.Width = abm.Width
r1.Height = abm.Height

'
' Set brush into graphics context
graphics1.Dispose()
graphics1 = Graphics.FromImage(abm)

' Dim Path
Dim path1 As New System.Drawing.Drawing2D.GraphicsPath
path1.FillMode = Drawing2D.FillMode.Alternate
path1.AddRectangle(r1)

'Dim brush
' mainform.alphapercent.text argument is 6-17 code for hatch percent
' we are establishing the percent of transparency for our overlay
' actually you cold use any of 52 hatch codes 6-17 are without pattern, 
' and represent a percent

' the forecolor is white, and white will be used as transparent color 
' when this brush is overlayed
' you could pass the transparent color from the other bitmap
' and the backcolor is transparent which retains origional for these pixels

Dim brush3 As New Drawing2D.HatchBrush _
(CInt(getarg2(MainForm.AlphaPercent.Text, "code")), _
System.Drawing.Color.White, System.Drawing.Color.Transparent)

graphics1.FillPath(brush3, path1)
brush3.Dispose()
path1.Dispose()

' the end result here is you have a brush with a percent of white, 
' this is added to any existing white

' that there was, when using this brush declare
' image.maketransparent=system.drawing.color.white

End Sub

以下图像来自我的项目 DesignLab(c) 2007。该程序可以管理高达 7200x7200 的位图,并已被用于在我的 Epson7800 上打印高达 56"x17" 的设计。我们已经将设计打印到丝绸上,用于丝绸围巾等。

© . All rights reserved.