Tuesday, September 4, 2012

Custom View

It's a very basic custom view extends android.view.View; simple draw background and a cross across the view. We will do more exercises base on it in coming posts.

Custom View


Create a custom view, MyView.java extends View.
package com.example.androiddraw;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {
 
 Paint BackPaint = new Paint();
 Paint MyPaint = new Paint();
 Context MyContext;

 public MyView(Context context) {
  super(context);
  init(context);
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init(context);
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init(context);
 }
 
 private void init(Context ctx){
  MyContext = ctx;
  
  BackPaint.setStyle(Paint.Style.FILL);
  BackPaint.setColor(Color.GRAY);
  
  MyPaint.setStyle(Paint.Style.STROKE);
  MyPaint.setColor(Color.WHITE);
  MyPaint.setStrokeWidth(3);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int w = MeasureSpec.getSize(widthMeasureSpec);
  int h = MeasureSpec.getSize(heightMeasureSpec);
  setMeasuredDimension(w, h);
 }

 @Override
 protected void onDraw(Canvas canvas) {
  canvas.drawRect(0, 0, getWidth(), getHeight(), BackPaint);
  canvas.drawLine(0, 0, getWidth(), getHeight(), MyPaint);
  canvas.drawLine(getWidth(), 0, 0, getHeight(), MyPaint);
 };
 
}


Modify the main code, MainActivity.java, to set it in ContentView.
package com.example.androiddraw;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        MyView myView = new MyView(this);
        setContentView(myView);
    }
    
}


Download the files.


Related examples:
- Paint.setShader() with SweepGradient
- LinearGradient example
- Draw bitmap on canvas
- Draw text with shadow on canvas
- Draw bitmap with shadow on canvas
- RadialGradient example
- Using ColorMatrixColorFilter
- Generate negative image using ColorMatrix
- LightingColorFilter example
- PorterDuffColorFilter example


No comments: