Draw Pint : Canvas « 2D Graphics « Android






Draw Pint

    


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.drawable.Drawable;

public class Pint{
  private Drawable bgFull, bgEmpty, bgFront;
  private Bitmap foam;
  private static final float WIDTH = 320;
  private static final float HEIGHT = 480;
  private static final float TOTAL = WIDTH*HEIGHT - 50*320;
  private float currentVolume = 0;
  
  float leftY=480, rightY=480;
  float foamHeight;
  
  public Pint(Drawable bgFull, Drawable bgEmpty, Drawable bgFront, Bitmap foam){
    this.bgEmpty = bgEmpty;
    this.bgEmpty.setBounds(0, 0, bgEmpty.getIntrinsicWidth(), bgEmpty.getIntrinsicHeight());
    this.bgFull = bgFull;
    this.bgFull.setBounds(0, 0, bgFull.getIntrinsicWidth(), bgFull.getIntrinsicHeight());
    this.bgFront = bgFront;
    this.bgFront.setBounds(0, 0, bgFront.getIntrinsicWidth(), bgFront.getIntrinsicHeight());
    this.foam = foam;
    foamHeight = foam.getHeight()/2;
  }
  
  private float angle  = 0f;
  private boolean full = false;
  
  public void setAngle(float angle) {
    this.angle = angle;
  }
  
  public float getCurrentVolume() {
    return currentVolume;
  }
  
  public void setCurrentVolume(float currentVolume) {
    this.currentVolume = currentVolume;
}
  
  public void draw(Canvas canvas){

    bgEmpty.draw(canvas);
    canvas.save();
  
    float emptyHeight = 0;
    if(!full){
      currentVolume += (10 * 320);
      if(currentVolume > TOTAL){
        full = true;
      }
    }

    emptyHeight = (float) (Math.tan(Math.toRadians(angle)) * WIDTH);
    
    float adjustedHeight = currentVolume / WIDTH; //normal height
    adjustedHeight = adjustedHeight <= 0? 2f : adjustedHeight;

    leftY = Math.max(-1000, HEIGHT - ( adjustedHeight + emptyHeight));
    rightY = Math.max(-1000, HEIGHT - (adjustedHeight - emptyHeight));
    
    if(currentVolume > WIDTH){
      Path p = new Path();
      p.moveTo(0, HEIGHT); //lower left
      p.lineTo(WIDTH, HEIGHT);
      p.lineTo(WIDTH, rightY);
      p.lineTo(0, leftY);
      canvas.clipPath(p);
      bgFull.draw(canvas);
      canvas.restore();    

      canvas.drawBitmapMesh(
          foam, 1, 1, new float[]{
              0, leftY-foamHeight, 320, rightY-foamHeight,
              0, leftY+foamHeight, 320, rightY+foamHeight,}, 0, null, 0, null);

    }
        
    if(leftY < 5 || rightY < 5){
      currentVolume *= 0.98;// -= (2000f);
      currentVolume -= 200f;
    }

    bgFront.draw(canvas);
  }
  
}

   
    
    
    
  








Related examples in the same category

1.Draw with Canvas
2.Canvas Layers
3.Translate Canvas
4.Sweep
5.Vertices
6.Scale To Fit
7.Class for the scribble/memo pad
8.Bezier interpolate