martes, 5 de agosto de 2014

Android: Drawing

Draw dashed box

public class DashedBox extends View {

 private Paint paint;


 public DetectionRectangle(Context context) {
  
  super(context);
  
  createPaint();
 }

 private void createPaint() {
  
  paint = new Paint();
  paint.setColor(Color.WHITE);
  paint.setStyle(Style.STROKE);
  paint.setStrokeWidth(convertToPx(2));
  paint.setPathEffect(new DashPathEffect(new float[] { 20, 5 }, 0));
  
  setLayerType(View.LAYER_TYPE_SOFTWARE, null); // Mandatory else it won't draw the dash but a full line
 }
 
 private int convertToPx(int dp) {
     // Get the screen's density scale
     final float scale = getResources().getDisplayMetrics().density;
     // Convert the dps to pixels, based on density scale
     return (int) (dp * scale + 0.5f);
 }

 public DetectionRectangle(Context context, AttributeSet attrs) {
  
  super(context, attrs);
  
  createPaint();
 }

 public DetectionRectangle(Context context, AttributeSet attrs, int defStyleAttr) {
  
  super(context, attrs, defStyleAttr);
  
  createPaint();
 }

 
 @Override
 protected void onDraw(Canvas canvas) {
  
  super.onDraw(canvas);
  
  canvas.drawLine(0, 0, getWidth(), 0, paint); // Top line
  canvas.drawLine(0, 0, 0, getHeight(), paint); // Left line
  canvas.drawLine(0, getHeight(), getWidth(), getHeight(), paint); // Bot line
  canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint); // Right line
 }
}

No hay comentarios:

Publicar un comentario