/ocr/worldreader/src/com/google/marvin/worldreader/RectsView.java
Java | 98 lines | 62 code | 16 blank | 20 comment | 3 complexity | be77b031f9f108e0c5435ca05dc97389 MD5 | raw file
1/* 2 * Copyright (C) 2009 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16package com.google.marvin.worldreader; 17 18import android.content.Context; 19import android.graphics.Canvas; 20import android.graphics.Matrix; 21import android.graphics.Paint; 22import android.graphics.Rect; 23import android.graphics.RectF; 24import android.util.AttributeSet; 25import android.util.Log; 26import android.view.View; 27 28import java.util.LinkedList; 29 30/** 31 * Displays colored bounding boxes scaled to screen resolution. 32 * 33 * @author alanv@google.com (Alan Viverette) 34 */ 35public class RectsView extends View { 36 private static final String TAG = "RectsView"; 37 38 private Matrix mMatrix; 39 private Paint mPaint; 40 private LinkedList<Pair> mRects; 41 42 public RectsView(Context context, AttributeSet attrs) { 43 super(context, attrs); 44 45 mRects = new LinkedList<Pair>(); 46 mPaint = new Paint(); 47 mPaint.setStyle(Paint.Style.STROKE); 48 mPaint.setStrokeWidth(5.0f); 49 } 50 51 public void addRect(Rect rect) { 52 if (rect != null) { 53 RectF rectf = new RectF(rect); 54 int argb = (int) (Math.random() * Integer.MAX_VALUE) | 0xFF000000; 55 Pair entry = new Pair(rectf, argb); 56 57 mMatrix.mapRect(rectf); 58 mRects.add(entry); 59 postInvalidate(); 60 } 61 } 62 63 public void setScaling(int srcW, int srcH, int dstW, int dstH) { 64 float scaleX = dstW / (float) srcW; 65 float scaleY = dstH / (float) srcH; 66 float scale = Math.min(scaleX, scaleY); 67 68 float scaledW = scale * srcW; 69 float scaledH = scale * srcH; 70 71 float deltaX = (dstW - scaledW) / 2.0f; 72 float deltaY = (dstH - scaledH) / 2.0f; 73 74 mMatrix = new Matrix(); 75 mMatrix.postScale(scale, scale); 76 mMatrix.postTranslate(deltaX, deltaY); 77 78 Log.i(TAG, "Set scaling to scale " + scale + " transform (" + deltaX + "," + deltaY + ")"); 79 } 80 81 @Override 82 public void onDraw(Canvas canvas) { 83 for (Pair entry : mRects) { 84 mPaint.setColor(entry.argb); 85 canvas.drawRect(entry.rectf, mPaint); 86 } 87 } 88 89 private class Pair { 90 public RectF rectf; 91 public int argb; 92 93 public Pair(RectF rectf, int argb) { 94 this.rectf = rectf; 95 this.argb = argb; 96 } 97 } 98}