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?

2
  • 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. Commented May 28, 2018 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 :) Commented May 28, 2018 at 14:22

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.