Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using canvas and bitmap in Android , how to get this image?

I am new in android. I am trying to draw this image(match statistic) enter image description here and fill the image with color with 10% to 100% . I tried this much and this is imageenter image description here

this is the code

public class DrawView extends View {
Paint paint = new Paint();

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

@Override
public void onDraw(Canvas canvas) {
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(3);
    canvas.drawRect(30, 30, 100, 100, paint);
    paint.setStrokeWidth(0);
    paint.setColor(Color.GRAY);
    canvas.drawRect(33, 60, 97, 97, paint);
    paint.setColor(Color.WHITE);
    canvas.drawRect(33, 33, 97, 60, paint);

}

Any Suggestion will be much helpful for me. Thanks in advance.

like image 624
Bishnu Dudhraj Avatar asked Nov 10 '16 07:11

Bishnu Dudhraj


People also ask

What is canvas and Bitmap in Android?

Canvas is the place or medium where perfroms/executes the operation of drawing, and Bitmap is responsible for storing the pixel of the picture you draw.

How do I view Bitmap in Android?

The ImageView class is pointed at a bitmap stored under one of the drawable folders in the res project folders. Start by creating a basic app project that will contain the ImageView and bitmap to display. Here the new project created in Android Studio is called Bitmap and an Empty Activity used.

How do I create a Bitmap in canvas?

To create a Bitmap from a resource, use the BitmapFactory method decodeResource(): Bitmap = BitmapFactory. decodeResource(getResources(), R. drawable.


1 Answers

I would prepare two images - fully filled and not filled (only stroke). Having that, load them as two Bitmap objects and then draw like that:

float fillProgress = 0.1f; // let's say image is 10% filled

canvas.drawBitmap(onlyStroke, 0f, 0f, null);  // draw just stroke first

canvas.save();
canvas.clipRect(
    0f,                                       // left
    getHeight() - fillProgress * getHeight(), // top
    getWidth(),                               // right
    getHeight()                               // bottom
);
canvas.drawBitmap(filled, 0f, 0f, null);      // region of filled image specified by clipRect will now be drawn on top of onlyStroke image
canvas.restore();

Using two images, outlined and filled e.g. below.

enter image description here enter image description here

The code above does the following:

  1. draw outline.
  2. apply clip (crop) area.
  3. draw filled shape with crop applied.
  4. remove clip, image as desired.

enter image description here

Applying different clip sizes, you can get the % of fill you require. e.g.

enter image description here

like image 189
Dmitry Zaytsev Avatar answered Oct 07 '22 02:10

Dmitry Zaytsev