0

I have an ImageView as shown below:

 <ImageView
    android:id="@+id/barchart"
    android:layout_width="100dp"
    android:layout_height="6dp"
    android:layout_below="@+id/stats"
    android:layout_marginTop="9dp"
    android:layout_toRightOf="@+id/model"
    android:background="@android:color/white" />

So, this image will be basically represented in the form of an white horizontal strip. Now, I want to color its ImageView width depending on a dynamic value. If value is 30dp then, 30dp of the image will be in one color and rest 70dp will be in white color.

So, the aim is basically to represent in the form of bar chart.

Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
Chaitanya
  • 3,399
  • 6
  • 29
  • 47

2 Answers2

1

The easiest way is to override View class and draw your bars manually. Maybe even not one stripe, but entire chart. It's very easy to do. Something like this:

class ChartView extends View {
    Paint paint = new Paint();
    List<Rect> stripes = new ArrayList<Rect>();
    List<Integer> colors = new ArrayList<Integer>();

    public ChartView(Context context) {
        super(context);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        for (Rect r : stripes) {
            paint.setColor(colors.get(stripes.indexOf(r)));
            canvas.drawRect(r, paint);
        }
    }
}

Of course using rects to store bars is a rather bad idea. Also, you have to alter the drawing part to achieve two-color bars, but I hope you get the idea.

http://developer.android.com/reference/android/graphics/Canvas.html http://developer.android.com/reference/android/graphics/Paint.html

Zielony
  • 16,239
  • 6
  • 34
  • 39
  • So, if we want something like above functionality, we definitely need to have two imageviews right ? I mean can't we achieve that thing using a single imageview ? – Chaitanya Mar 19 '13 at 09:50
  • You can, using proper bitmaps or gradients, but I don't think it's a good idea to build a chart using ImageViews. – Zielony Mar 19 '13 at 10:22
  • Ok. Is there any reason for not using imageview ? – Chaitanya Mar 19 '13 at 11:12
  • 1
    Because it's a View, so it's quite heavy. Android has to measure and layout it, create textures for hardware acceleration, use sampling, antialiasing, access stripe bitmap memory and do lots of stuff just to draw white/red/blue rectangles. Custom View is always much faster and easier to maintain when it comes to complex views such as charts. – Zielony Mar 19 '13 at 12:31
  • Ok. So, basically when we are dealing with canvas and stuff which is lower in level than the actual imageviews. Thanks :) – Chaitanya Mar 19 '13 at 13:48
1

Possible Duplicate: banded background with two colors?

You can see the both xml way of creating it and the dynamic way of setting it as well.

Community
  • 1
  • 1
Triode
  • 11,309
  • 2
  • 38
  • 48