Android implements an example of drawing operations in View via onDraw

  • 2020-05-17 06:28:03
  • OfStack

The Android drawing operation, which is implemented by inheriting View, is implemented in the onDraw function.
Here's a simple example:

public class AndroidTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyView mv = new MyView(this);
        setContentView(mv);
    }

    public class MyView extends View {
     MyView(Context context) {
      super(context);
     }

  @Override
  protected void onDraw(Canvas canvas) {
   // TODO Auto-generated method stub
   super.onDraw(canvas);

   //  First of all define 1 a paint 
   Paint paint = new Paint(); 
   //  Draw a rectangular area - Solid rectangular  
   //  Set the color  
   paint.setColor(Color.BLUE); 
   //  Set the style - fill  
   paint.setStyle(Style.FILL); 
   //  draw 1 A rectangular  
   canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint); 
   //  Draw hollow rectangle  
   //  Set the color  
   paint.setColor(Color.RED); 
   //  Set the style - A hollow rectangular  
   paint.setStyle(Style.STROKE); 
   //  draw 1 A rectangular  
   canvas.drawRect(new Rect(10, 10, 100, 30), paint); 
   //  Paint with words  
   //  Set the color  
   paint.setColor(Color.GREEN); 
   //  Paint with words  
   canvas.drawText("Hello", 10, 50, paint); 
   //  drawing  
   //  Generate bitmaps from resource files  
   Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); 
   //  drawing  
   canvas.drawBitmap(bitmap, 10, 60, paint); 
  }

    }
}


Related articles: