# B4J Question[Solved:distance to color values]...

##### Active Member
Longtime User
Dear friends, how to convert distance into color values? The application is to plot distance values to spatial coordinates with color coding.

#### Erel

##### B4X founder
Staff member
Longtime User
B4X:
``````Sub InterpolateColor(StartClr As Int, EndClr As Int, Fraction As Float) As Int
Dim clr As Int
For i = 0 To 3
Dim shift As Int = 8 * i
Dim src As Int = Bit.UnsignedShiftRight(Bit.And(StartClr, Bit.ShiftLeft(0xff, shift)), shift)
Dim target As Int = Bit.UnsignedShiftRight(Bit.And(EndClr, Bit.ShiftLeft(0xff, shift)), shift)
clr = clr + Bit.ShiftLeft(Max(0, Min(255, src + (target - src) * Fraction)), shift)
Next
Return clr
End Sub``````

Usage example:
B4X:
``````Dim x As B4XView = MainForm.RootPane
For i = 0 To 100
x.Color = InterpolateColor(xui.Color_Green, xui.Color_Magenta, i / 100)
Sleep(30)
Next``````

##### Active Member
Longtime User
Wow , that was fast.
Actually I am using the following to draw points:
B4X:
``cvs1.DrawCircle(i,j,3,fx.Colors.Blue,True,1)``
where I want "fx.Colors.Blue" to be replaced by the mapped color!
Apologies for a naive question.

#### Erel

##### B4X founder
Staff member
Longtime User
Switch to B4XCanvas. It uses integers (same as in B4A and B4i) instead of the color objects.

##### Active Member
Longtime User
I did switch to B4XCanvas following is my code:
B4X:
``````Dim v As B4XView =Pane2

For i=0 To 350 Step 20
For j=0 To 500 Step 20
v.Color = InterpolateColor(xui.Color_red, xui.Color_blue, Rnd(0,100)/ 100)
cvs1.DrawCircle(i,j,5,v.Color,True,1)
Next
Next``````
But the pane2 color also changes and I expect only the circle color should change!

##### Active Member
Longtime User
The code is great, but still only two colors and their combinations are available. It would be great if more colors can be made available.

#### Erel

##### B4X founder
Staff member
Longtime User
The code I posted does a linear interpolation between two colors. I'm not sure what you mean with more colors. You can split the distance into several sections and add more colors (red to green and then green to blue for example).

Replies
9
Views
6K
Android Code Snippet [B4X] HexToColor and ColorToHex
Replies
6
Views
6K
Replies
4
Views
2K
Replies
97
Views
177K
Replies
172
Views
60K