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

使用颜色矩阵和图像属性 alpha 混合两个位图

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.52/5 (9投票s)

2007年1月11日

CPOL
viewsIcon

32387

这里是另一个真正的像素级别混合。

引言

我知道有很多关于 Alpha 混合的例子,但其中许多都不是真正的混合,比如我在一篇文章中的例子。 还有一些将透明度管理称为混合,还有一些是真正复杂的变换和合并。

我一直相信应该有一个简单的 .NET 解决方案,只需要大约 5 行代码…… 这就是它了!

Public Sub SetAlphaRGB(ByRef abm As Image)

Dim bitm As New Bitmap(abm)

' I actually got help on this from using visual studio F1
' Initialize the color matrix.

Dim mxItems As Single()() = { _
New Single() {1, 0, 0, 0, 0}, _
New Single() {0, 1, 0, 0, 0}, _
New Single() {0, 0, 1, 0, 0}, _
New Single() {0, 0, 0, 128, 0}, _ Note that sets alpha at 128 50%
New Single() {0, 0, 0, 0, 1}}

Dim colorMatrix As New System.Drawing.Imaging.ColorMatrix(mxItems)

' Create an ImageAttributes object and set its color matrix.

Dim imageAtt As New System.Drawing.Imaging.ImageAttributes()

imageAtt.SetColorMatrix(colorMatrix, _
                        System.Drawing.Imaging.ColorMatrixFlag.Default, _
                        System.Drawing.Imaging.ColorAdjustType.Bitmap)

' look at properties of imageattributes also can set threshold and gamma
so this routine can handle most of your image manipulations

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

Dim r2 As RectangleF
r2.X = 0
r2.Y = 0
r2.Width = bm.Width
r2.Height = bm.Height 

'
graphics1.Dispose()
graphics1 = Graphics.FromImage(bm)

Dim brush3 As New TextureBrush(bitm, r1, imageAtt)
brush3.WrapMode = Drawing2D.WrapMode.Tile ' if you want to tile else delete

graphics1.CompositingMode = Drawing2D.CompositingMode.SourceOver
graphics1.FillRectangle(brush3, r2) ' I didnt test but fill path should allow
                                    ' overlay in irregular polygon etc.

'draw image could be used, but if you want to tile a fill option is needed
graphics1.DrawImage(bitm, New Rectangle(0, 0, 1700, 1700), 0, 0,_
                    bitm.Width, bitm.Height, GraphicsUnit.Pixel, imageAtt)

brush3.Dispose()
graphics1.Dispose()
MainForm.PictureBox1.Refresh() ' Required by my project
SetGraphics(MainForm.PictureBox1) ' Required by my project

End Sub

我的孙女在一个 DesignLab(c) 2007 设计上进行了平铺。 这是在 128 Alpha (50%) 下。 这确实只需要大约 5 行代码。 如果你调整图像属性,你也可以管理阈值和伽玛值。

Sample image

使用颜色矩阵和图像属性进行 Alpha 混合的两个位图 - CodeProject - 代码之家
© . All rights reserved.