2

I'm trying to merge 2 colors and to do so I created a very simple function:

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.

I tried changing the type of the variables first to Integer and then to Double with no change in the results.

I also tried switching from the \ operator to the / one but still no change.

Does the type of the variables (color.A) influence the execution?

des
  • 67
  • 1
  • 8
  • 4
    VB.NET is a bit unusual for .NET languages, adding 2 bytes produces a Byte result, not an Integer. So it is not the assignment that overflowed, it was the addition. Use CInt() to force an Integer addition, like a = CByte((CInt(color1.A) + color2.A) \ 2). The CByte is necessary to keep Option Strict On happy. – Hans Passant May 28 '18 at 14:16
  • Yes, thanks, I tried changing the funcion with an Int variable instead of the first color and it worked, so I suspected it was as you explained. Thanks for the clarification :) – des May 28 '18 at 14:22

1 Answers1

3

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. Color.FromArgb takes 4 integers anyway. 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)
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939