detect face from image and crop face from that photo - android

I have done coding in that i am successfully getting face with rectangle drawing now i want to crop that rectangle area. if there are many rectangle( mean many faces) than user can select one of the face or rectangle and that rectangle areal should be cropped can any body help me...
Below is my code
class AndroidFaceDetector extends Activity {
public String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
path = bundle.getString("mypath");
setContentView(new myView(this));
}
class myView extends View {
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
System.out.println("CONSTRUCTOR");
System.out.println("path = "+path);
if (path != null) {
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeFile(path, BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
} else {
Toast.makeText(AndroidFaceDetector.this, "Please Try again", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDraw(Canvas canvas) {
System.out.println("ON DRAW IS CALLED");
if (myBitmap != null) {
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for (int i = 0; i < numberOfFaceDetected; i++) {
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect((int) (myMidPoint.x - myEyesDistance), (int) (myMidPoint.y - myEyesDistance),
(int) (myMidPoint.x + myEyesDistance), (int) (myMidPoint.y + myEyesDistance), myPaint);
}
}
}
}
}

Related

How to auto fit the canvas for editing the image in android

I am trying draw on the image. Now I am using following class.
public class DrawingPaint extends View implements View.OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, mBitmapPaint;
public ArrayList<PathPoints> paths = new ArrayList<PathPoints>();
private ArrayList<PathPoints> undonePaths = new ArrayList<PathPoints>();
private Bitmap mBitmap;
private int color;
private int x, y;
private String textToDraw = null;
private boolean isTextModeOn = false;
int lastColor = 0xFFFF0000;
static final float STROKE_WIDTH = 15f;
public DrawingPaint(Context context/*, int color*/) {
super(context);
//this.color = color;
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
/*mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(STROKE_WIDTH);
mPaint.setTextSize(30);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();*/
}
public void colorChanged(int color) {
this.color = color;
mPaint.setColor(color);
}
public void setColor(int color) {
mPaint = new Paint();
this.color = color;
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(STROKE_WIDTH);
mPaint.setTextSize(30);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// mBitmap = AddReportItemActivity.mPhoto;
mBitmap = CustomGalleryHandler.getmInstance().getBitmapSend();
float xscale = (float) w / (float) mBitmap.getWidth();
float yscale = (float) h / (float) mBitmap.getHeight();
if (xscale > yscale) // make sure both dimensions fit (use the
// smaller scale)
xscale = yscale;
float newx = (float) w * xscale;
float newy = (float) h * xscale; // use the same scale for both
// dimensions
// if you want it centered on the display (black borders)
mBitmap = Bitmap.createScaledBitmap(mBitmap, this.getWidth(),
this.getHeight(), true);
// mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
for (PathPoints p : paths) {
mPaint.setColor(p.getColor());
Log.v("", "Color code : " + p.getColor());
if (p.isTextToDraw()) {
canvas.drawText(p.textToDraw, p.x, p.y, mPaint);
} else {
canvas.drawPath(p.getPath(), mPaint);
}
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
}
private void drawText(int x, int y) {
this.x = x;
this.y = y;
paths.add(new PathPoints(color, textToDraw, true, x, y));
// mCanvas.drawText(textToDraw, x, y, mPaint);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isTextModeOn) {
touch_start(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if (!isTextModeOn) {
touch_move(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (isTextModeOn) {
drawText((int) x, (int) y);
invalidate();
} else {
touch_up();
invalidate();
}
break;
}
return true;
}
public void onClickUndo() {
try {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
invalidate();
} else {
}
} catch (Exception e) {
e.toString();
}
}
public void onClickRedo() {
try {
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
invalidate();
} else {
}
} catch (Exception e) {
e.toString();
}
}
}
The following method is used in Activity extended class
public class GalleryImageFullScreen extends Activity implements View.OnClickListener {
private ImageView mFullScreenImage;
private ImageView /*mWhiteColor,*//* mGreenColor, mSkyBlueColor, mYellowColor, mRedColor, mBlackColor,*/ mUndoIcon,
mPaintImageSave, mPaintImageDelete, mRedoIcon;
RoundedImageView mWhiteColor, mGreenColor, mSkyBlueColor, mYellowColor, mRedColor, mBlackColor;
// private Signature mSignature;
private RelativeLayout mDrawLayout;
private DrawingPaint mDrawViewSignature;
private AlertDialog mAlertDialog = null;
Bitmap bitmapss;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery_fullscreen);
super.onCreate(savedInstanceState);
mUndoIcon =(ImageView)findViewById(R.id.erase_icon);
mFullScreenImage=(ImageView)findViewById(R.id.img_fullscreen);
mDrawLayout=(RelativeLayout)findViewById(R.id.img_fullscreen_layout);
mPaintImageSave=(ImageView)findViewById(R.id.paint_img_save);
mPaintImageDelete=(ImageView)findViewById(R.id.paint_img_delete);
mRedoIcon=(ImageView)findViewById(R.id.img_redo);
mWhiteColor.setOnClickListener(this);
mGreenColor.setOnClickListener(this);
mSkyBlueColor.setOnClickListener(this);
mYellowColor.setOnClickListener(this);
mRedColor.setOnClickListener(this);
mBlackColor.setOnClickListener(this);
mUndoIcon.setOnClickListener(this);
mPaintImageSave.setOnClickListener(this);
mPaintImageDelete.setOnClickListener(this);
mRedoIcon.setOnClickListener(this);
// mSignature = new Signature(GalleryImageFullScreen.this, null);
try {
Intent i=getIntent();
Bitmap image = null;
image = BitmapFactory.decodeFile(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().setBitmapSend(image);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
mDrawLayout.getLayoutParams().width = imageWidth;
mDrawLayout.getLayoutParams().height = imageHeight;
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(imageWidth,imageHeight);
// mDrawLayout.setLayoutParams(layout_description);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(imageWidth,
imageHeight, Bitmap.Config.ARGB_8888);
mDrawViewSignature = new DrawingPaint(GalleryImageFullScreen.this/*, lastColor*/);
mDrawViewSignature.setDrawingCacheEnabled(true);
mDrawViewSignature.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
mDrawViewSignature.layout(0, 0, mDrawViewSignature.getMeasuredWidth(),
mDrawViewSignature.getMeasuredHeight());
mDrawViewSignature.buildDrawingCache(true);
Canvas canvas = new Canvas(mSignatureBitmapImage);
Drawable bgDrawable = mDrawLayout.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
mDrawLayout.draw(canvas);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
mSignatureBitmapImage.compress(Bitmap.CompressFormat.PNG, 50, bs);
}
catch (Exception e)
{
Logger.d("", "" + e.toString());
}
mDrawViewSignature.setColor(getResources().getColor(R.color.black));
mDrawLayout.addView(mDrawViewSignature);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.paint_img_save:
try {
Bitmap editedImage = Bitmap.createBitmap(mDrawViewSignature
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, mDrawViewSignature.getWidth(), mDrawViewSignature.getHeight(),
true);
if(editedImage!=null) {
final Bitmap finalEditedImage = editedImage;
mAlertDialog = Alerts.getInstance().createConfirmationDialog(this, this.getResources().getString(R.string.painting_image_save), new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bitmap editedImage = Bitmap.createBitmap(mDrawViewSignature
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, mDrawViewSignature.getWidth(), mDrawViewSignature.getHeight(),
true);*/
//saveImageToInternalStorage(finalEditedImage);
storeImage(finalEditedImage);
PreferenceForCustomCamera.getInstance().setEditedURL(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
callToGalleyActivity();
mAlertDialog.dismiss();
}
});
mAlertDialog.show();
}
}
catch (Exception e)
{
Logger.d("paint_img_save",""+e.toString());
}
break;
case R.id.paint_img_delete:
try {
if (!PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen().equals("") && !PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen().equals("null")) {
mAlertDialog = Alerts.getInstance().createConfirmationDialog(this, this.getResources().getString(R.string.painting_image_path_delete), new View.OnClickListener() {
#Override
public void onClick(View v) {
// DatabaseHelper.getInstance().deleteParticularVideoPath(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().deleteParticularImages(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
CustomGalleryHandler.getmInstance().deleteParticularImageFromInternalStorage(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
callToGalleyActivity();
mAlertDialog.dismiss();
}
});
}
mAlertDialog.show();
}
catch (Exception e)
{
Logger.d("paint_img_delete",""+e.toString());
}
break;
case R.id.img_redo:
mDrawViewSignature.onClickRedo();
break;
}
}
private void saveImageToInternalStorage(Bitmap finalBitmap) {
try {
File myDir = new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
myDir.mkdirs();
Logger.d("ListOfPhoto",""+myDir.getAbsolutePath());
Logger.d("ListOfPhotoRename",""+PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
for(File files: myDir.listFiles())
{
Logger.d("ListOfPhoto",""+files.getAbsolutePath());
Logger.d("ListOfPhotoRename",""+PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
}
Picasso.with(getApplicationContext()).load(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen()).skipMemoryCache();
/*Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + "3680" + ".png";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}*/
try {
if(myDir.exists())
{
myDir.delete();
}
FileOutputStream out = new FileOutputStream(myDir);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e)
{
Logger.d("saveImageToInternalStorage",""+e.toString());
}
}
private void storeImage(Bitmap image) {
File pictureFile = new File(PreferenceForCustomCamera.getInstance().getImagePathForGalleryFullScreen());
if (pictureFile.exists()) {
pictureFile.delete();
}
//clearImageDiskCache();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Logger.d("GalleryImage", "File not found: " + e.getMessage());
} catch (IOException e) {
Logger.d("GalleryImage", "Error accessing file: " + e.getMessage());
}
}
public boolean clearImageDiskCache() {
File cache = new File(getApplicationContext().getCacheDir(), "picasso-cache");
if (cache.exists() && cache.isDirectory()) {
return deleteDir(cache);
}
return false;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
The following code used in my xml for draw.
<RelativeLayout
android:id="#+id/img_fullscreen_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edit_components_bar"
android:layout_centerHorizontal="true">
<ImageView
android:id="#+id/img_fullscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
It is working fine when I use Landscape images. But when I use Portrait image, image getting stretched. Please let me know how to make the canvas fit to the image.
Thanks in advance
I alter this code:
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, imageWidth, imageHeight);
RectF outRect = new RectF(0, 0, imageWidth-10, imageHeight-10);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(image,0,0,imageWidth,
imageHeight, m,true);
I used this code also. But Not working:
Matrix m = mFullScreenImage.getImageMatrix();
RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
RectF viewRect = new RectF(0, 0, mFullScreenImage.getWidth(), mFullScreenImage.getHeight());
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
Bitmap mSignatureBitmapImage = Bitmap.createBitmap(image,0,0,imageWidth,
imageHeight, m,true);

Scale the Bitmap to screen in Live wallpaper

I'm new in Android Programming I'm Trying to make slideshow animated live wallpaper and all ok but the problem is when I set the wallpaper the scale of image is stretched to screen I want it to scale to all the phone screens and when swipe the wallpaper get the right part of image I Want Advice about this problem.
my code is :
public class CustomWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
return new WallpaperEngine();
}
class WallpaperEngine extends Engine {
//Duration between slides in milliseconds
private final int SLIDE_DURATION = 8;
private int[] mImagesArray;
private int mImagesArrayIndex = 0;
private Thread mDrawWallpaper;
private String mImageScale = "Fit to screen";
private CustomWallpaperHelper customWallpaperHelper;
public WallpaperEngine() {
customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
mImagesArray = new int[] {R.drawable.image_1,R.drawable.image_2,R.drawable.image_3,R.drawable.image_4,R.drawable.image_5,R.drawable.image_6,R.drawable.image_7,R.drawable.image_8,R.drawable.image_9,R.drawable.image_10,R.drawable.image_11,R.drawable.image_12,R.drawable.image_13,R.drawable.image_14,R.drawable.image_15,R.drawable.image_16,R.drawable.image_17,R.drawable.image_18,R.drawable.image_19,R.drawable.image_20,R.drawable.image_21,R.drawable.image_22,R.drawable.image_23,R.drawable.image_24,R.drawable.image_25,R.drawable.image_26,R.drawable.image_27,R.drawable.image_28,R.drawable.image_29,R.drawable.image_30,R.drawable.image_31,R.drawable.image_32,R.drawable.image_33,R.drawable.image_34,R.drawable.image_35,R.drawable.image_36,R.drawable.image_37,R.drawable.image_38,R.drawable.image_39,R.drawable.image_40,R.drawable.image_41};
mDrawWallpaper = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
drawFrame();
incrementCounter();
Thread.sleep(SLIDE_DURATION);
}
} catch (Exception e) {
//
}
}
});
mDrawWallpaper.start();
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
//Draw background
customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
}
}
and the other class is:
public class CustomWallpaperHelper {
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to screen";
public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen";
private Context mContext;
private Resources mResources;
private Point screenSize = new Point();
private Bitmap bgImageScaled;
private Point bgImagePos = new Point(0, 0);
public CustomWallpaperHelper(Context mContext, Resources mResources) {
this.mContext = mContext;
this.mResources = mResources;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenSize.x = display.getWidth();
screenSize.y = display.getHeight();
;
}
private void scaleBackground() {
String imageScale = "Stretch to screen";
Bitmap bgImage = null;
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
bgImagePos = new Point(0, 0);
bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true);
}
}
public void setBackground(Canvas canvas) {
if (bgImageScaled != null) {
canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null);
} else {
canvas.drawColor(0xff000000);
}
}
public int getScreenWidth() {
return screenSize.x;
}
public int getScreenHeight() {
return screenSize.y;
}
public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) {
Point imagePos = new Point();
imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x)) / 2;
imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y)) / 2;
return imagePos;
}
public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) {
PointF canvasScale = new PointF(1f, 1f);
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = getScreenHeight() / (1f * imageHeight);
} else {
boolean tooWide = false;
boolean tooTall = false;
if (getScreenWidth() < imageWidth) {
tooWide = true;
}
if (getScreenHeight() < imageHeight) {
tooTall = true;
}
if (tooWide && tooTall) {
int x = imageWidth / getScreenWidth();
int y = imageHeight / getScreenHeight();
if (x > y) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
} else if (tooWide) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else if (tooTall) {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
}
return canvasScale;
}
}
I want Advice for this problem.
Thanks.
no need to do anything just Replace your below method with my code.
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
I would suggest that you crop the images instead of resizing them. Something like:
Rect r = new Rect(left, top, right, bottom);
Bitmap croppedImage = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1){
InputStream in = mContentResolver.openInputStream(mSaveUri);
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(in, false);
croppedImage = decoder.decodeRegion(r, null);
} else {
final int width = r.width();
final int height = r.height();
croppedImage = Bitmap.createBitmap(mBitmap, r.left, r.top, width, height);
croppedImage.setDensity(croppedImage.getDensity() * mOutputX / width);
}
return croppedImage;
Hope this helps...

How crop bitmap of selected area on canvas?

I am making an application I am unable to one issue last 3 days doing google as much possible.I make a circle on canvas and want to crop image that part and show that image in zoom mode.My first step is like in screen here:-
in this I am selecting area.here is my code used by me for this.
private float x, y;
private boolean zooming = false;
private Paint mPaint;
private Matrix mmatrix;
private Shader mShader;
private Bitmap mBitmap;
private List<Point> mpoints;
private List<MyPoints> mpointlist;
private Path mpath;
private Canvas mcanvas;
private Bitmap mresult_bitmap, resultingImage,finalbitmap;
private Context mcontext;
private boolean bfirstpoint = false;
private Point mfirstpoint = null;
private Point mlastpoint = null;
public CircularZoomView(Context context) {
super(context);
mcontext = context;
mpath = new Path();
mpoints = new ArrayList<Point>();
setBackgroundResource(R.drawable.testing);
mPaint = new Paint();
mresult_bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.testing);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.RED);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (zooming && resultingImage!=null) {
zooming = false;
ShowImage(resultingImage);
canvas.drawBitmap(resultingImage,mmatrix, null);
}
boolean first = true;
for (int i = 0; i < mpoints.size(); i += 2) {
Point point = mpoints.get(i);
if (first) {
first = false;
mpath.moveTo(point.x, point.y);
} else if (i < mpoints.size() - 1) {
Point next = mpoints.get(i + 1);
mpath.quadTo(point.x, point.y, next.x, next.y);
} else {
mlastpoint = mpoints.get(i);
mpath.lineTo(point.x, point.y);
}
}
canvas.drawPath(mpath, mPaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
x = event.getX();
y = event.getY();
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
if (bfirstpoint) {
if (comparepoint(mfirstpoint, point)) {
mpoints.add(mfirstpoint);
addCircleFromPath(mpath);
} else {
mpoints.add(point);
}
} else {
mpoints.add(point);
}
if (!(bfirstpoint)) {
mfirstpoint = point;
bfirstpoint = true;
}
invalidate();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
zooming = false;
this.invalidate();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
zooming = true;
mlastpoint = point;
if (mpoints.size() > 12) {
if (!comparepoint(mfirstpoint, mlastpoint)) {
mpoints.add(mfirstpoint);
addCircleFromPath(mpath);
}
}
this.invalidate();
break;
default:
break;
}
return true;
}
public Bitmap getCroppedBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
void ShowImage(Bitmap mbitmap) {
Display display = ((MainActivity) mcontext).getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
float imageWidth = (float)mbitmap.getWidth();
float imageHeight = (float)mbitmap.getHeight();
float newHeight = imageHeight / (imageWidth / screenWidth);
float newWidth = screenWidth;
float scaleWidth = screenWidth / imageWidth;
float scaleHeight = newHeight / imageHeight;
SetImageMatrix(mbitmap,scaleWidth,scaleHeight);
}
void SetImageMatrix(Bitmap image,float scaleWidth, float scaleHeight) {
mmatrix = new Matrix();
mmatrix.setTranslate(40,40);
mmatrix.postScale(scaleWidth/2, scaleHeight/2);
/*image.setImageMatrix(mmatrix);
image.setScaleType(ScaleType.MATRIX);
image.invalidate();*/
}
private boolean comparepoint(Point first, Point current) {
int left_range_x = (int) (current.x - 3);
int left_range_y = (int) (current.y - 3);
int right_range_x = (int) (current.x + 3);
int right_range_y = (int) (current.y + 3);
if ((left_range_x < first.x && first.x < right_range_x)
&& (left_range_y < first.y && first.y < right_range_y)) {
if (mpoints.size() < 10) {
return false;
} else {
return true;
}
} else {
return false;
}
}
private void addCircleFromPath(Path path){
RectF bounds = new RectF();
path.computeBounds(bounds, true);
int width = (int) (bounds.right-bounds.left);
int height = (int) (bounds.bottom-bounds.top);
if(width<20 && height<20){
path.reset();
return;
}
int radius ;
if(width>=height)
radius = Math.round(((width/2)));
else radius = Math.round((int) ((height/2)));
/*CircleTagObject circle = new CircleTagObject((int)bounds.left+width/2, (int)bounds.top+height/2, radius, crossBitmap, tagBitmap,circleArray.size(),
ImageEditorView.this);
circleArray.add(circle);
tagBallID = circleArray.size() - 1;
dragEnable = true;*/
resultingImage = getCroppedBitmap(Bitmap.createBitmap(mresult_bitmap,0,0,200,200));
mcanvas = new Canvas(resultingImage);
path.reset();
resetView();
invalidate();
}
public void resetView() {
mpoints.clear();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.RED);
invalidate();
}
If I create hard coded bitmap like above its showing good but not crop bitmap of selected part.Like this image.
but when add exact coordinate of selected area Like as:-
resultingImage = getCroppedBitmap(Bitmap.createBitmap(mresult_bitmap,(int)bounds.left,(int)bounds.top,width,height));
Then exception occure:-
07-12 10:58:56.700: E/MessageQueue-JNI(12310): java.lang.IllegalArgumentException: y + height must be <= bitmap.height()
07-12 10:58:56.700: E/MessageQueue-JNI(12310): at android.graphics.Bitmap.createBitmap(Bitmap.java:565)
07-12 10:58:56.700: E/MessageQueue-JNI(12310): at android.graphics.Bitmap.createBitmap(Bitmap.java:530)
07-12 10:58:56.700: E/MessageQueue-JNI(12310): at com.intel.view.CircularZoomView.addCircleFromPath(CircularZoomView.java:237)
I know why This exception occurs but unable to find solution how crop image of selected part.Thanks in advance.
I know its too late for your solution but this may help to others Use of this code
help you to come out from this problem.

Clicking on image view to draw canvas on it, moves image view vertically on each touch event. why?

I want to draw canvas on image view
I am using concept of Finger Paint but it is not working
public class show_image extends Activity implements OnTouchListener,ColorPickerDialog.OnColorChangedListener {
ImageView img_vw_show;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
float x1, y1, x2, y2;
Bitmap bmp;
int i = 1, width, height;
private static final float MINP = 0.25f;
// private static final float MAXP = 0.75f;
int w, h;
Bitmap mBitmap, bMap, newBitmap;
Canvas mCanvas;
Path mPath;
Paint mBitmapPaint, mPaint;
MaskFilter mEmboss;
MaskFilter mBlur;
BufferedInputStream buf;
MyView mv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_image);
System.out.println("oncreate method called");
img_vw_show = (ImageView) this.findViewById(R.id.img_vw_show);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
// mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
img_vw_show.setOnTouchListener((OnTouchListener) this);
String responseImagePath = this.getIntent().getStringExtra(
"responseImagePath");
String selectedImagePath = this.getIntent().getStringExtra(
"selectedImagePath");
System.out.println("responseImagePath in show image========"
+ responseImagePath);
System.out.println("selectedImagePath in show image========"
+ selectedImagePath);
Boolean selectedImagePathFlag = false;
if (selectedImagePath == null) {
selectedImagePathFlag = true;
} else if (selectedImagePath.equals("")) {
selectedImagePathFlag = true;
}
if (selectedImagePathFlag) {
if (responseImagePath != null && !responseImagePath.equals("")) {
URL url1;
InputStream in;
try {
url1 = new
// URL("http://mail.sshanghvi.com:8080/sacplupload/checklist/"+responseImagePath);
URL("http://192.168.1.49:82/uploads/" + responseImagePath);
in = url1.openStream();
// Read the inputstream
buf = new BufferedInputStream(in);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bMap = BitmapFactory.decodeStream(buf, null, o2);
img_vw_show.setImageBitmap(bMap);
width = bMap.getWidth();
height = bMap.getHeight();
System.out.println("Width and Height is==" + width + " & "
+ height);
mv = new MyView(show_image.this, bMap);
System.out.println("Setting the Myview");
mv.invalidate();
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
} else {
Toast.makeText(getApplicationContext(), "Image Not Available",
Toast.LENGTH_SHORT).show();
}
} else {
File imgFile = new File(selectedImagePath);
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering mode
bfOptions.inPurgeable = true; // Tell to gc that whether it needs
// free memory, the Bitmap can be
// cleared
bfOptions.inInputShareable = true; // Which kind of reference will
// be used to recover the Bitmap
// data after being clear, when
// it will be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
Bitmap myBitmap = BitmapFactory.decodeFile(
imgFile.getAbsolutePath(), bfOptions);
img_vw_show.setImageBitmap(myBitmap);
}
}
public class MyView extends View {
public MyView(Context c, Bitmap img) {
super(c);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(8);
setWillNotDraw(false);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6,
3.5f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
Bitmap newBitmap;
Canvas newCanvas;
public void onDraw(Canvas canvas) {
super.onDraw(newCanvas);
newBitmap= Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
newCanvas= new Canvas(newBitmap);
System.out.println("canvas == "+canvas);
System.out.println("newCanvas == "+newCanvas);
System.out.println("onDraw Called");
img_vw_show.draw(newCanvas);
newCanvas.drawBitmap(newBitmap, 0, 0, mBitmapPaint);
newCanvas.drawPath(mPath, mPaint);
img_vw_show.setImageBitmap(newBitmap);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
System.out.println("Touch Start Called");
onDraw(newCanvas);
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
System.out.println("Touch Move Called");
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
System.out.println("Touch Up Called");
mPath.lineTo(mX, mY);
// commit the path to our offscreen
newCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
}
private static final int COLOR_MENU_ID = Menu.FIRST;
private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
private static final int BLUR_MENU_ID = Menu.FIRST + 2;
private static final int ERASE_MENU_ID = Menu.FIRST + 3;
private static final int SRCATOP_MENU_ID = Menu.FIRST + 4;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z');
/****
* Is this the mechanism to extend with filter effects? Intent intent =
* new Intent(null, getIntent().getData());
* intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
* menu.addIntentOptions( Menu.ALTERNATIVE, 0, new ComponentName(this,
* NotesList.class), null, intent, 0, null);
*****/
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
mPaint.setXfermode(null);
mPaint.setAlpha(0xFF);
switch (item.getItemId()) {
case COLOR_MENU_ID:
new ColorPickerDialog(this, this, mPaint.getColor()).show();
return true;
case EMBOSS_MENU_ID:
if (mPaint.getMaskFilter() != mEmboss) {
mPaint.setMaskFilter(mEmboss);
} else {
mPaint.setMaskFilter(null);
}
return true;
case BLUR_MENU_ID:
if (mPaint.getMaskFilter() != mBlur) {
mPaint.setMaskFilter(mBlur);
} else {
mPaint.setMaskFilter(null);
}
return true;
case ERASE_MENU_ID:
// mPaint.setXfermode(new
// PorterDuffXfermode(PorterDuff.Mode.CLEAR));
return true;
case SRCATOP_MENU_ID:
// mPaint.setXfermode(new
// PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
mPaint.setAlpha(0x80);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void colorChanged(int color) {
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mv.touch_start(x, y);
v.invalidate();
break;
case MotionEvent.ACTION_MOVE:
mv.touch_move(x, y);
v.invalidate();
break;
case MotionEvent.ACTION_UP:
mv.touch_up();
v.invalidate();
break;
}
return true;
}
}
Even i faced the same problem in my app. Drawing the shapes from the canvas onto the imageViews and later updating them each time did not seem to work.
I accomplished the same by extracting the shape onto my UI class and there i wrote a method
showView(View v, color color)
{
}
And called it in my main activity whenever required. In my app the scenario was to changethe colors dynamically of the canvas.
So I worked upon it like that and it worked. Hope it helps.
Canvas Class:
public void init()
{
basePaint = new Paint();
basePaint.setColor(Color.RED);
basePaint.setStrokeWidth(2);
basePaint.setStyle(Paint.Style.FILL_AND_STROKE);
paint = new Paint();
paint.setStrokeWidth(2);
paint.setColor(color);
triPaint = new Paint();
triPaint.setColor(Color.RED);
triPaint.setStrokeWidth(2);
triPaint.setStyle(Paint.Style.FILL_AND_STROKE);
triPaint1 = new Paint();
triPaint1.setColor(Color.RED);
triPaint1.setStrokeWidth(2);
triPaint1.setStyle(Paint.Style.FILL_AND_STROKE);
diffPaint = new Paint();
diffPaint.setColor(color);
diffPaint.setStrokeWidth(2);
diffPaint.setStyle(Paint.Style.FILL_AND_STROKE);
Log.i("color","="+color);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
}
#Override
public void onDraw(Canvas canvas) {
Log.d("check","="+color);
Log.e("check","after set:"+buf);
Log.i("new view ", " on draw ");
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
/*basePaint.setStyle(Paint.Style.FILL);
basePaint.setStrokeWidth(3);
basePaint.setColor(Color.RED);
canvas.drawLine(0,40,80,40,basePaint);*/
path = new Path();
path.moveTo(0, 30); /*For Borders*/
path.lineTo(30, 0);
path.lineTo(-30, 0);
path.close();
path.offset(20, -5);
canvas.drawPath(path, paint);
diffPaint.setStyle(Paint.Style.FILL);
diffPaint.setStrokeWidth(3);
diffPaint.setColor(color); //To fill The Triangle
Log.d("Filling","Triangles");
diffPath = new Path();
diffPath.moveTo(0, 30);
Log.d("After","1st line");
diffPath.lineTo(30, 0);
Log.d("After","2nd line");
diffPath.lineTo(-30, 0);
Log.d("After","3rd line");
diffPath.close();
diffPath.offset(20, -5);
Log.d("Locating","Arrow");
canvas.drawPath(diffPath, diffPaint);
Log.d("Drew","Arrow");
Log.d("Color","="+color);
triPaint.setStyle(Paint.Style.FILL);
triPaint.setStrokeWidth(100);
triPaint.setColor(Color.BLACK);
triPath = new Path();
triPath.moveTo(0, -20);
triPath.lineTo(20, 0);
triPath.lineTo(-20, 0); //To Fill the extra Space
triPath.close();
triPath.offset(42,26);
canvas.drawPath(triPath, triPaint);
triPaint1.setStyle(Paint.Style.FILL);
triPaint1.setStrokeWidth(100);
triPaint1.setColor(Color.BLACK);
triPath1 = new Path();
triPath1.moveTo(0, -20);
triPath1.lineTo(20, 0);
triPath1.lineTo(-20, 0);
triPath1.close();
triPath1.offset(-2,26);
canvas.drawPath(triPath1, triPaint1);
}
UI class:
public void show(View anchor,int color) {
preShow();
int xPos, yPos, arrowPos;
mDidAction = false; /*Setting the position of arrows drawn using canvas in UI*/
int[] location = new int[2];
anchor.getLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0]
+ anchor.getWidth(), location[1] + anchor.getHeight());
mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootHeight = mRootView.getMeasuredHeight();
if (rootWidth == 0) {
rootWidth = mRootView.getMeasuredWidth();
}
int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
int screenHeight = mWindowManager.getDefaultDisplay().getHeight();
if ((anchorRect.left + rootWidth) > screenWidth) {
xPos = anchorRect.left - (rootWidth - anchor.getWidth());
xPos = (xPos < 0) ? 0 : xPos;
arrowPos = anchorRect.centerX() - xPos;
} else {
if (anchor.getWidth() > rootWidth) {
xPos = anchorRect.centerX() - (rootWidth / 2);
} else {
xPos = anchorRect.left;
}
arrowPos = anchorRect.centerX() - xPos;
}
int dyTop = anchorRect.top;
int dyBottom = screenHeight - anchorRect.bottom;
boolean onTop = (dyTop > dyBottom) ? true : false;
if (onTop) {
if (rootHeight > dyTop) {
yPos = 15;
LayoutParams l = mScroller.getLayoutParams();
l.height = dyTop - anchor.getHeight();
} else {
yPos = anchorRect.top - rootHeight;
}
} else {
yPos = anchorRect.bottom;
if (rootHeight > dyBottom) {
LayoutParams l = mScroller.getLayoutParams();
l.height = dyBottom;
}
}
showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos,color);
/*updating color of arrow which is the shape drawn in canvas*/
container.setBackgroundColor(color);
setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);
mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
Main Activity:
Whenever the shape needs to be updated by a modification of color:
btn1 = (Button) this.findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("In","View");
quickAction.show(v,Color.BLUE);
/*By passing the color the color is getting updated and modified on each button click for the shape drawn using canvas on the imageView*/
}
});

how to change the edit text position dynamically

I am new to Android. I am trying to implement photo tagging application where we can tag the faces like facebook photo tagging. I am able to find the faces and draw the rectangles over faces.
But I am trying to place an EditText(to write name) at face recognized rectangle when the user touches those rectangles. And once it is done I need to disable the EditText and need show TextView (name). Please find code below and help me.
Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
myEditTet = new EditText(this);
myView custom = new myView(this);
layout.addView(myEditTet);
myEditTet.setVisibility(View.GONE);
// layout.addView(myTextView);
// myTextView.setVisibility(View.GONE);
layout.addView(custom, params); // Of course, this too
setContentView(layout);
}
private class myView extends View {
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.face3, BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight,
numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for (int i = 0; i < numberOfFaceDetected; i++) {
android.media.FaceDetector.Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
dx = (int) (myMidPoint.x - myEyesDistance);
dy = (int) (myMidPoint.y - myEyesDistance);
dz = (int) (myMidPoint.x + myEyesDistance);
dt = (int) (myMidPoint.y + myEyesDistance);
canvas.drawRect((int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
(int) (myMidPoint.x + myEyesDistance),
(int) (myMidPoint.y + myEyesDistance), myPaint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
myEditTet.setVisibility(View.VISIBLE);
if (event.getX() > dx && event.getX() < dz && event.getY() > dy
&& event.getY() < dt) {
Log.i("SARDAR", "RECT TOUCH 1111");
}
return super.onTouchEvent(event);
}
}
}
i have done it by this way...
params.setmargin(left,top,right,bottom);
layout.addView(myeditText,params);
arguments are of int types

Categories

Resources