Tensorflow - Edit image to print out location of bounding boxes? - java

I have an android application and I've integrated my own custom tensorflow lite model.
I can print out the object category and probability score but I'm at a loss on how to draw the bounding boxes of the object on the image that is uploaded.
Here is my code that I have where I set the image into a ImageView.
// SET THE IMAGE
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100)
{
imageBox.setImageURI(data.getData());
Uri uri = data.getData();
try {
img = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I am integrating the model.
predictBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img, 128, 128, true);
try {
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
// Releases model resources if no longer used.
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type and its accuracy score
objecttv.setText(category);
scoretv.setText(Float.toString(score));
} catch (IOException e) {
// TODO Handle the exception
}
}
});
What do I need to do to make use of RectF location = detectionResult.getLocationAsRectF(); ?
I am using a static image and not actually tracking the movement in realtime.

Answer modified after question changed.
You can draw the bounding boxes with Canvas. Override onDraw() in the view where you want to draw the rectangle. Attention, this codes only works for one bounding box. Otherwise you have to implement a for loop. You should not call the canvas onDraw function directly from the activity. Here is a complete example:
Your tracker class:
// Init your canvas view
DrawView mCanvasView = (DrawView) findViewById(R.id.canvasView);
// ...
predictBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img, 128, 128, true);
try {
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
mCanvasView.drawBoundingBox()
// Releases model resources if no longer used.
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type and its accuracy score
objecttv.setText(category);
scoretv.setText(Float.toString(score));
} catch (IOException e) {
// TODO Handle the exception
}
}
});
Implement this canvas view:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint boxPaint;
public static Canvas mCanvas;
public DrawView(Context context) {
super(context);
boxPaint = new Paint();
}
public void drawBoundingBox() {
// Refresh the view by calling onDraw function
invalidate();
}
#Override
public void onDraw(Canvas canvas, AttributeSet attrs) {
// Draw what you want
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(location, boxPaint);
}
}
Define your Draw view in xml of your tracker class
<your.package.name.DrawView
android:id="#+id/R.id.canvasView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Related

Android - draw rectangle on uploaded bitmap image

I am using a tflite model and I am trying to draw a RectF on the image where the object is detected.
Here is my CameraActivity.java class where I am detecting the object.
predictBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img, 128, 128, true);
try {
DrawView drawView = new DrawView(getApplicationContext());
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
// Releases model resources if no longer used.
mCanvas.drawBoundingBox();
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type and its accuracy score
mCanvasView.drawRect();
objecttv.setText(category);
scoretv.setText(Float.toString(score));
} catch (IOException e) {
// TODO Handle the exception
}
}
}
);
Here is my DrawView.java class
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 DrawView extends View {
Paint boxPaint;
public static Canvas mCanvas;
public DrawView(Context context) {
super(context);
boxPaint = new Paint();
}
public void drawBoundingBox() {
// Refresh the view by calling onDraw function
invalidate();
}
public void onDraw(Canvas canvas, AttributeSet attrs) {
// Draw what you want
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(location, boxPaint);
}
}
In my activity_camera.xml , I added the drawview to match the image I am uploading.
<com.example.aPROJECT.DrawView
android:id="#+id/canvasView"
android:layout_width="281dp"
android:layout_height="324dp"
android:layout_marginTop="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:id="#+id/imageView"
android:layout_width="281dp"
android:layout_height="324dp"
android:layout_marginTop="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_menu_gallery"
tools:ignore="ImageContrastCheck" />
In the CameraActivity.java , on line mCanvas.drawBoundingBox(); it cannot access the mCanvas from the DrawView.java class.
On line mCanvasView.drawRect(); it cannot resolve the symbol .
What am I missing here?
There are several problems:
if you want to access a static field outside of its class in Java you need to either specify the class name like this DrawView.mCanvas or to use a static import (add a line
import static /*class.package.name.here.*/DrawView.mCanvas;
above the class declaration and then you can use mCanvas directly)
drawBoundingBox() is a method in DrawView, not canvas so the correct way to call would be drawView.drawBoundingBox()
even if the class would compile you'd get a NullPointerException when drawRoundingBox() was called because mCanvas has not been initialized in DrawView
the canvas in a View is only a temporary variable as parameter to onDraw used to create the user interface at that moment in time (each frame) and is not meant to be used outside of that method since it points/refers to a video memory buffer that is continuously changed
What you should do is create a Canvas for the Bitmap you're trying to draw on and use it (you don't need a view to alter a bitmap):
//if img is the bitmap you want to draw on
Canvas c = new Canvas(img); //before createScaledBitmap()
drawBoundingBox(c);// move onDraw code to drawBoundingBox()
// and the latter method to CameraActivity
//Should you need to get the bitmap screenshot of a view simply draw it:
Bitmap vscr = Bitmap.createBitmap(yourView.getWidth(), yourView.getHeight(), Bitmap.Config.ARGB_8888);
//ensure the view was added to the layout (measured) so that its width and height are greater than zero when you create the bitmap
yourView.draw(vscr);
Example
public class CameraActivity extends ActivityCompat {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
predictBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img, 128, 128, true);
try {
//DrawView drawView = new DrawView(getApplicationContext());
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
// Releases model resources if no longer used.
Canvas canvas = new Canvas(img);
drawBoundingBox(canvas, location);
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type and its accuracy score
mCanvasView.drawRect();
objecttv.setText(category);
scoretv.setText(Float.toString(score));
} catch (IOException e) {
// TODO Handle the exception
}
}
});
} //onCreate
void drawBoundingBox(Canvas canvas, RectF location) {
// Draw what you want
Paint boxPaint = new Paint();
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(location, boxPaint);
}
}

how to get byte array from camera preview in java android?

I'm a complete noob . I've managed to write and understand this code after reading this http://developer.android.com/guide/topics/media/camera.html .
But now i want to get the byte array for preview and then convert it to bitmap . But i want to do this in real time without be forced to save a picture file in storage . Please , help!
Here is my program code.
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
String TAG = null;
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
mCamera.setDisplayOrientation(90);
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
String TAG = null;
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
private PictureCallback mPicture = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
// TODO: Implement this method
}
};
}
And main activity :
public class MainActivity extends Activity
{ private Camera mCamera;
private CameraPreview mPreview;
int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.frame);
preview.addView(mPreview);
}
public static Camera getCameraInstance()
{
Camera c = null;
try
{
c = Camera.open();}
catch (Exception e)
{ System.out.println("blamjjjh");}
return c;
}
public void releasec(){
mCamera.release();
}
#Override
protected void onStop()
{
super.onStop();
releasec();
}
}
As detailed in the Android Developer docs here (which you might have already read), add an implementation of the PictureCallback interface (see the example below) to your Activity. Also you can use BitmapFactory to then convert the byte array that gets passed back to a Bitmap. Then you can use this as required.
NOTE:
I would also read the docs here on handling Bitmaps efficiently in relation to memory as you might get OutOfMemory errors if you're manipulating Bitmaps.
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//create a Bitmap from the byte array
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
//use your Bitmap
}
};
You then need to pass this into the takePicture() method against your camera instance e.g.
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
Hope this helps! :-)

Android image view top crop

I'm developing an android application and i need a header to use at the top of the screen similar to an action bar ..... i want it to be transparent but when you start to scroll the view all the content of the view goes behind it so i decided to use an image view (it has to be different in any fragment that's why i didn't use action bar) so i used a frame layout and fixed the image view at the top with the height of 50 and i used the same background of the main view as the source of the image view .... my problem is the scale type i used Center Crop in the main view and it's perfect but it's useless in the header so i'm looking for some thing like this :
which is exactly like center crop but crops from the top of the image .
i used this link but it wasn't what i'm looking for .....
Top Crop ImageView:
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class TopCropImageView extends ImageView {
private Matrix mMatrix;
private boolean mHasFrame;
#SuppressWarnings("UnusedDeclaration")
public TopCropImageView(Context context) {
this(context, null, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopCropImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopCropImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mHasFrame = false;
mMatrix = new Matrix();
// we have to use own matrix because:
// ImageView.setImageMatrix(Matrix matrix) will not call
// configureBounds(); invalidate(); because we will operate on ImageView object
}
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
boolean changed = super.setFrame(l, t, r, b);
if (changed) {
mHasFrame = true;
// we do not want to call this method if nothing changed
setupScaleMatrix(r-l, b-t);
}
return changed;
}
private void setupScaleMatrix(int width, int height) {
if (!mHasFrame) {
// we have to ensure that we already have frame
// called and have width and height
return;
}
final Drawable drawable = getDrawable();
if (drawable == null) {
// we have to check if drawable is null because
// when not initialized at startup drawable we can
// rise NullPointerException
return;
}
Matrix matrix = mMatrix;
final int intrinsicWidth = drawable.getIntrinsicWidth();
final int intrinsicHeight = drawable.getIntrinsicHeight();
float factorWidth = width/(float) intrinsicWidth;
float factorHeight = height/(float) intrinsicHeight;
float factor = Math.max(factorHeight, factorWidth);
// there magic happen and can be adjusted to current
// needs
matrix.setTranslate(-intrinsicWidth/2.0f, 0);
matrix.postScale(factor, factor, 0, 0);
matrix.postTranslate(width/2.0f, 0);
setImageMatrix(matrix);
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
// We do not have to overide setImageBitmap because it calls
// setImageDrawable method
}
I managed to get this working with the PhotoView library that can be found here:
https://github.com/chrisbanes/PhotoView
All you need to do is set the library up and on the image view you are using set the scale type to CENTER_CROP. Then in the library go to the PhotoViewAttacher.java file and under the method updateBaseMatrix() where the code for CENTER_CROP is, change it to the following:
else if (mScaleType == ScaleType.CENTER_CROP) {
float scale = Math.max(widthScale, heightScale);
mBaseMatrix.postScale(scale, scale);
//Changed dy = 0 for top crop
mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
0);
Basically, you set dy=0 so that the matrix stays at the top of the image on the y axis and doesn't center it. And the CENTER_CROP scale type will behave like a TOP_CROP
Your approach is kind of hacky, I suggest you take a look at using a Sticky Fragment (for example).
The Video, Source and Sample can be found in this Google+ Post

Android: how to get default camera settings of builtin camera application

I have seen lots of tutorial and information but i could not find any single place how to use the default settings of the existing camera application into any other customized camera application. I have seen the sharpness of the image and its focus is very fine in the built-in camera application. Now i am creating my own application with my customized features but i am still unable to make it sharp and non-blurry... I dont want to use Intent technique of the camera because i have to do some image processing afterward.
I have used zooming but strangely zoom is not properly working ...like it works in built-in camera application
here is my surface change code
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
Log.e(TAG, "surfaceChanged");
// XXX stopPreview() will crash if preview is not running
if (mPreviewRunning) {
mCamera.stopPreview();
}
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
mFrameWidth = w;
mFrameHeight = h;
// selecting optimal camera preview size
{
double minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes)
{
if (Math.abs(size.height - h) < minDiff)
{
mFrameWidth = size.width;
mFrameHeight = size.height;
minDiff = Math.abs(size.height - h);
}
}
}
try
{
//params.set("rotation", 180);
//params.set("orientation", "landscape");
//params.set("auto", "WHITE_BALANCE_AUTO");//WHITE_BALANCE_AUTO
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
params.setPreviewSize(mFrameHeight, mFrameWidth);
mCamera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
params.setPreviewSize(mFrameWidth, mFrameHeight);
}
if(display.getRotation() == Surface.ROTATION_180)
{
params.setPreviewSize(mFrameHeight, mFrameWidth);
}
if(display.getRotation() == Surface.ROTATION_270)
{
params.setPreviewSize(mFrameWidth, mFrameHeight);
mCamera.setDisplayOrientation(180);
}
if(params.isZoomSupported())
{
Log.e(TAG, params.getZoom()+"surfaceChanged camer zoom"+params.getMinExposureCompensation());
params.setZoom(params.getMaxZoom());
params.setExposureCompensation(1);
// params.setColorEffect("none");
params.setWhiteBalance(params.WHITE_BALANCE_AUTO);
params.setFocusMode(params.FOCUS_MODE_AUTO);
params.setSceneMode(params.SCENE_MODE_ACTION);
}
params.set("auto", "FOCUS_MODE_AUTO");
params.setPreviewSize(mFrameWidth,mFrameHeight);
mCamera.setParameters(params);
mCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
}
Kindly let me know how to make the camera preview exactly same as the built in application one.
You mean a fullscreen camera preview?
I use this code:
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //no title
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //no status bar, etc
and this:
setContentView(R.layout.main);
addContentView(overlay, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
((FrameLayout) findViewById(R.id.preview)).addView(preview);
the first snippet sets the app to fullscreen and hide title and status bar.
the second snipppet adds my overlay (extended View) to the main layout.
Here my xml and java code:
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Overlay.java:
class Overlay extends View {
String text = "";
String textBearing = "Bearing: ";
public Overlay(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(16);
canvas.drawText(text, 20, 20, paint);
canvas.drawText(textBearing, 20, 50, paint);
super.onDraw(canvas);
}
}
And my activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //no title
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //fullscreen
overlay = new Overlay(this);
setContentView(R.layout.main);
addContentView(overlay, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
camera = getCameraInstance(); //camera.open();
preview = new Preview(this, camera);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
}
Hope it helps
I encountered the same problem with you. After reading the source code of the builtin camera app, and comparing the focus processing of builtin camera and my own camera, I realized the problem is on autofocus.
So try this:
mCamera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
mCamera.takePicture(null, null, mPicture);
}
});
which makes the result image as sharp as builtin camera.
The documents is here.

ImageView getLocationtOnScreen android

I am trying to get the coordinates of the image on the screen. I currently have an ImageView within an activity. I understand that the getLocationOnScreen() method can only be called once the layout has been created, so calling this method within the oncreate function would return [0,0]. But I do not know how to get this method to return the correct values. I have tried overiding various superclass methods, like the onstart method or the onTouchEvent method and it still returns [0,0] to me. The code I currently have is as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
// Some code here after which ..
image = (ImageView) findViewById(R.id.imageVfi);
image.setImageBitmap(imageData.entrySet().iterator().next().getValue());
}
Then I have the onStart method which I have overriden
#Override
public void onStart()
{
super.onStart();
image.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int[] dim = new int[2];
image.getLocationOnScreen(dim);
new AlertDialog.Builder(DisplayPicture.this)
.setIcon(R.drawable.icon)
.setTitle("Touch coordinates : " +
String.valueOf(dim[0]) + "x" + String.valueOf(dim[1]))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}).show();
// image calculations go here
return true;
}
});
}
This returns 0X0 to me. Any help is much appreciated.
ImageView does not offer a way to get the location of its image on screen. You can only query the location of the ImageView itself. You can try to use ImageView.getImageMatrix() but I'm not sure we populate it when the image is simply centered (as opposed to scaled, etc.)
Solution after following advice given above
Solution:
Following the advice provided by Romain Guy below, I was able to get the co-ordinates but adding the following code to the onStart overidden method.
display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
float rowStart=0, rowEnd=0, columnStart=0, columnEnd=0;
if(orientation ==0)
{
final Matrix matrix = image.getImageMatrix();
float[] values = new float[9];
matrix.getValues(values);
rowStart = values[0];
columnStart = values[5];
rowEnd = image.getWidth()-rowStart;
columnEnd = image.getHeight()-columnStart;
}else if(orientation == 1)
{
final Matrix matrix = image.getImageMatrix();
float[] values = new float[9];
matrix.getValues(values);
rowStart = values[2];
columnStart = values[3];
rowEnd = image.getWidth()-rowStart;
columnEnd = image.getHeight()-columnStart;
}
If it's only the image view that you have in your activity, then it will be positioned by default in the top left corner with coordinates 0x0.

Categories