[英]VB.NET OverflowException on very small operation
I'm trying to merge 2 colors and to do so I created a very simple function: 我正在尝试合并2种颜色,为此,我创建了一个非常简单的函数:
Public Function MixColors(color1 As Color, color2 As Color) As Color
Dim a, r, g, b As Byte
a = (color1.A + color2.A) \ 2
r = (color1.R + color2.R) \ 2
g = (color1.G + color2.G) \ 2
b = (color1.B + color2.B) \ 2
Return Color.FromArgb(a, r, g, b)
End Function
The problem is I get an OverflowException at the very first operation and I can't understand why. 问题是我在第一次操作时收到OverflowException,但我不明白为什么。
I tried changing the type of the variables first to Integer and then to Double with no change in the results. 我尝试先将变量的类型更改为Integer,然后更改为Double,结果不变。
I also tried switching from the \\ operator to the / one but still no change. 我也尝试从\\运算符切换到/ one,但仍然没有任何变化。
Does the type of the variables (color.A) influence the execution? 变量的类型(color.A)会影响执行吗?
As Hans has already commented, if you add two bytes(like color1.A+color1.B
) you get a byte as result which has a max value of 255. You have to cast it to Int32
, for example with CInt
. 正如Hans所说,如果添加两个字节(例如color1.A+color1.B
),则会得到一个结果字节,其最大值为255。您必须将其转换为Int32
,例如使用CInt
。 Color.FromArgb
takes 4 integers anyway. 无论如何, Color.FromArgb
需要4个整数。 So following should work: 所以以下应该工作:
Dim a, r, g, b As Int32
a = (CInt(color1.A) + CInt(color2.A)) \ 2
r = (CInt(color1.R) + CInt(color2.R)) \ 2
g = (CInt(color1.G) + CInt(color2.G)) \ 2
b = (CInt(color1.B) + CInt(color2.B)) \ 2
Return Color.FromArgb(a, r, g, b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.