To Examples

Drawing1 Example

Goal

Directions

  1. Create a project named Drawing1. Leave the layout and activity files with their default names.
  2. Set up a linear layout with these attributes set: id to layout, layout width and height to match_parent, orientation set to vertical, and layout margin to 32dp.
  3. Create a MyView class with this code:
    package it372.drawing1;
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.view.View;
    
    public class MyView extends View {
    
        public MyView(Context context) {
            super(context);
        }
    
        @Override
        public void onDraw(Canvas canvas) {
            Paint paint = new Paint( );
            canvas.drawColor(
                Color.parseColor("#ffa0a0"));
            paint.setColor(Color.BLUE);
            canvas.drawCircle(100, 100, 50, paint);
            paint.setStrokeWidth(10);
            System.out.println(canvas.getWidth());
            System.out.println(canvas.getHeight());
            canvas.drawLine(150, 150, 300, 300, paint);
            paint.setTextSize(50.0f);
            paint.setColor(Color.WHITE);
            canvas.drawText("Test Drawing", 200, 100, paint);
        }
    }
    
  4. Add these lines to the activity code file:
    LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    MyView mv = new MyView(this);
    layout.addView(mv);
    
  5. Run your app to test it. Here is the emulator screenshot.
  6. Here are the final files for the layout, MyView class, and activity:
        activity_main.xml   MyView.java    MainActivity.java