I am trying to get rgb value at a point on image where user taps. I am using following code to achieve that.
imageView.setOnTouchListener(new ImageView.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int x=0;
int y=0;
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
}
Log.v("RGB",pixel+ " :R: "+redValue+ " G: "+blueValue+ " B:"+greenValue);
return true; }
});
But it returns same value of RGB for every point on the image that is "-10197916 :R: 100 G: 100 B:100".
I have even used int x=(int)event.getIntX();
int y=(int)event.getIntY();
But result is always same. What did I miss?
You have used:
int x=0;
int y=0;
You need to use:
int x = (int)event.getX();
int y = (int)event.getY();
This one worked,problem was to get right x,y as:
imageView.setOnTouchListener(imgSourceOnTouchListener);
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
System.out.println(
"touched position: "
+ String.valueOf(eventX) + " / "
+ String.valueOf(eventY));
System.out.println(
"touched position: "
+ String.valueOf(x) + " / "
+ String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
System.out.println(
"drawable size: "
+ String.valueOf(bitmap.getWidth()) + " / "
+ String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
if(x < 0){
x = 0;
}else if(x > bitmap.getWidth()-1){
x = bitmap.getWidth()-1;
}
if(y < 0){
y = 0;
}else if(y > bitmap.getHeight()-1){
y = bitmap.getHeight()-1;
}
int touchedRGB = bitmap.getPixel(x, y);
System.out.println("touched color: " + "#" + Integer.toHexString(touchedRGB));
return true;
}};
iView_image1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
int color = 0;
try {
color = bmp.getPixel((int) event.getX(), (int) event.getY());
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
} catch (Exception e) {
}
return false;
}
});
Related
I am trying to get the rgb value from an image but I always get a different value even on the same pixel.
I used following code:
imageView=(ImageView)findViewById(R.id.imageView);
final Bitmap bitmap = ((BitmapDrawable)
imageView.getDrawable()).getBitmap();
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v,MotionEvent event) {
int x= (int)event.getX();
int y= (int)event.getY();
int pixel = bitmap.getPixel(x, y);
int redValue = Color.red(pixel);
int greenValue = Color.green(pixel);
int blueValue = Color.blue(pixel);
// Toast.makeText(MainActivity.this,String.format("#%02x%02x%02x", redValue,
greenValue, blueValue), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, "R= " + redValue + "G= " + greenValue +
"B= " + blueValue, Toast.LENGTH_LONG).show();
// Toast.makeText(MainActivity.this,""+x+"\tY "+y,Toast.LENGTH_LONG).show();
return false;
}
});
this is the code i am using to get starting x,y coordinates. i also need width and height of rectangle drawn.
this code i have taken from a website link- http://android-er.blogspot.in/2013/09/detect-touch-and-draw-rect-on-bitmap.html
please provide solution
public class MainActivity extends Activity {
Button btnLoadImage;
TextView textSource;
ImageView imageResult, imageDrawingPane;
final int RQS_IMAGE1 = 1;
Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;
Bitmap bitmapDrawingPane;
Canvas canvasDrawingPane;
projectPt startPt;
projectPt endpt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (Button)findViewById(R.id.loadimage);
textSource = (TextView)findViewById(R.id.sourceuri);
imageResult = (ImageView)findViewById(R.id.result);
imageDrawingPane = (ImageView)findViewById(R.id.drawingpane);
btnLoadImage.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}});
imageResult.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
textSource.setText("ACTION_DOWN- " + x + " : " + y);
startPt = projectXY((ImageView)v, bitmapMaster, x, y);
break;
case MotionEvent.ACTION_MOVE:
textSource.setText("ACTION_MOVE- " + x + " : " + y);
drawOnRectProjectedBitMap((ImageView)v, bitmapMaster, x, y);
break;
case MotionEvent.ACTION_UP:
textSource.setText("ACTION_UP- " + x + " : " + y);
drawOnRectProjectedBitMap((ImageView)v, bitmapMaster, x, y);
finalizeDrawing();
break;
}
return true;
}});
}
class projectPt{
int x;
int y;
projectPt(int tx, int ty){
x = tx;
y = ty;
}
}
private projectPt projectXY(ImageView iv, Bitmap bm, int x, int y){
if(x<0 || y<0 || x > iv.getWidth() || y > iv.getHeight()){
//outside ImageView
return null;
}else{
int projectedX = (int)((double)x * ((double)bm.getWidth()/(double)iv.getWidth()));
int projectedY = (int)((double)y * ((double)bm.getHeight()/(double)iv.getHeight()));
return new projectPt(projectedX, projectedY);
}
}
private void drawOnRectProjectedBitMap(ImageView iv, Bitmap bm, int x, int y){
if(x<0 || y<0 || x > iv.getWidth() || y > iv.getHeight()){
//outside ImageView
return;
}else{
int projectedX = (int)((double)x * ((double)bm.getWidth()/(double)iv.getWidth()));
int projectedY = (int)((double)y * ((double)bm.getHeight()/(double)iv.getHeight()));
//clear canvasDrawingPane
canvasDrawingPane.drawColor(Color.TRANSPARENT, Mode.CLEAR);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(4);
canvasDrawingPane.drawRect(startPt.x, startPt.y, projectedX, projectedY, paint);
imageDrawingPane.invalidate();
// textSource.setText(x + ":" + y + "/" + iv.getWidth() + " : " + iv.getHeight() + "\n" +
// projectedX + " : " + projectedY + "/" + bm.getWidth() + " : " + bm.getHeight()
textSource.setText(startPt.x + ":" + startPt.y + "/" + iv.getWidth() + " : " + iv.getHeight() + "\n" +
projectedX + " : " + projectedY+ "/" + bm.getWidth() + " : " + bm.getHeight()
);
}
}
private void finalizeDrawing(){
canvasMaster.drawBitmap(bitmapDrawingPane, 0, 0, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap tempBitmap;
if(resultCode == RESULT_OK){
switch (requestCode){
case RQS_IMAGE1:
source = data.getData();
textSource.setText(source.toString());
try {
tempBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source));
Config config;
if(tempBitmap.getConfig() != null){
config = tempBitmap.getConfig();
}else{
config = Config.ARGB_8888;
}
bitmapMaster = Bitmap.createBitmap(
tempBitmap.getWidth(),
tempBitmap.getHeight(),
config);
canvasMaster = new Canvas(bitmapMaster);
canvasMaster.drawBitmap(tempBitmap, 0, 0, null);
imageResult.setImageBitmap(bitmapMaster);
bitmapDrawingPane = Bitmap.createBitmap(
tempBitmap.getWidth(),
tempBitmap.getHeight(),
config);
canvasDrawingPane = new Canvas(bitmapDrawingPane);
imageDrawingPane.setImageBitmap(bitmapDrawingPane);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
}
Before drawing
Rect rect = new Rect(startPt.x, startPt.y, projectedX, projectedY);
canvasDrawingPane.drawRect(rect,paint);
width = rect.width();
height = rect.height();
imageDrawingPane.invalidate();
Here is your answer.
Here int projectedX and int int projectedY contains width and height of rectangle drawn.
You can make both global and access anywhere in the class.
Like this..
//rectangle width and height
int projectedX;
int projectedY;
//end
Button btnLoadImage;
TextView textSource;
ImageView imageResult, imageDrawingPane;
Now access projectedX & projectedY to get width and height anywhere.
I am trying to play two sound together when two button is touch together at the same time. I have button1 and button2, while button1 is touch, button2 wont play the sound. But when I put my finger off button1 then touching button2 plays the sound.
I have tried googling around but couldn't find an answer.
What I wanted to do is clear. Play two sound together when two buttons are touch together.
Below is my code so far.
public class MultitouchtestActivity extends MultiTouchActivity {
/** Called when the activity is first created. */
private Button btn1;
private Button btn2;
SoundPool soundPool;
AudioManager audioManager;
int soundId;
int kID, sID;
#Override
public void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
super.onCreate(savedInstanceState);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
//the maximum number of simultaneous streams for this SoundPool object
int maxStreams = 4;
//the audio stream type as described in AudioManager
int streamType = AudioManager.STREAM_MUSIC;
//the sample-rate converter quality. Currently has no effect. Use 0 for the default.
int srcQuality = 0;
soundPool = new SoundPool(maxStreams, streamType, srcQuality);
soundPool.setOnLoadCompleteListener(soundPoolOnLoadCompleteListener);
soundId = soundPool.load(this, R.raw.c, 1);
kID = soundPool.load(this, R.raw.k, 1);
sID = soundPool.load(this, R.raw.s, 1);
btn1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
float vol = audioManager.getStreamVolume(
AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
float leftVolume = vol/maxVol;
float rightVolume = vol/maxVol;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(kID,
leftVolume,
rightVolume,
priority,
no_loop,
normal_playback_rate);
return true;
}
return false;
}
});
btn2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
float vol = audioManager.getStreamVolume(
AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
float leftVolume = vol/maxVol;
float rightVolume = vol/maxVol;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(sID,
leftVolume,
rightVolume,
priority,
no_loop,
normal_playback_rate);
return true;
}
return false;
}
});
}
SoundPool.OnLoadCompleteListener soundPoolOnLoadCompleteListener = new SoundPool.OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status)
{
if(status==0)
{
btn1.setEnabled(true);
btn2.setEnabled(true);
}
else
{
Toast.makeText(MultitouchtestActivity.this,"SoundPool.load() fail", Toast.LENGTH_LONG).show();
}
}
};
}
public class MultiTouchActivity extends Activity implements OnTouchListener {
private View parent;
public void onCreate(Bundle instance)
{
super.onCreate(instance);
parent = findViewById(android.R.id.content).getRootView();
parent.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
for (int ptrIndex = 0; ptrIndex < event.getPointerCount(); ptrIndex++) {
// index of the pointer which starts this Event
int actionPointerIndex = event.getActionIndex();
// resolve the action as a basic type (up, down or move)
int actionResolved = event.getAction() & MotionEvent.ACTION_MASK;
if (actionResolved < 7 && actionResolved > 4) {
actionResolved = actionResolved - 5;
}
if (actionResolved == MotionEvent.ACTION_MOVE) {
dealEvent(ptrIndex, event, v, actionResolved);
Log.v("tag", "move" + ptrIndex);
} else {
dealEvent(actionPointerIndex, event, v, actionResolved);
}
}
return false;
}
private void dealEvent(int actionPointerIndex, MotionEvent event,
View eventView, int actionresolved) {
int rawX, rawY;
int location[] = { 0, 0 };
eventView.getLocationOnScreen(location);
// Log.v("tag", location + "");
rawX = (int) event.getX(actionPointerIndex) + location[0];
rawY = (int) event.getY(actionPointerIndex) + location[1];
ArrayList<View> views = getTouchedViews(rawX, rawY, actionresolved);
// dumpEvent(event);
for (View view : views) {
int x, y;
view.getLocationOnScreen(location);
x = rawX - location[0];
y = rawY - location[1];
// Log.v("tag", "touched" + view.toString());
/*
* view.onTouchEvent(MotionEvent.obtain(event.getDownTime(),
* event.getEventTime(), event.getActionMasked(), x, y,
* event.getMetaState()));
*/
// MotionEvent me = MotionEvent.obtain(event);
MotionEvent me = MotionEvent.obtain(event.getDownTime(),
event.getEventTime(), actionresolved, x, y,
event.getPressure(actionPointerIndex),
event.getPressure(actionPointerIndex),
event.getMetaState(), event.getXPrecision(),
event.getYPrecision(), event.getDeviceId(),
event.getEdgeFlags());
me.setLocation(x, y);
// Log.v("tag", "oldeventid: " + event.getAction() + " #" +
// actionPointerIndex+ " id" + ptrId+ " resolved "+ actionResolved);
// Log.v("tag", "neweventid: " + me.getAction() + " #" +
// actionPointerIndex+ " id" + ptrId+ " resolved "+ actionResolved);
if (!me.equals(event)) {
/*
* Log.v("tag", "actionindex: " + actionPointerIndex +
* " resolved: " + actionPointerIndex + " to " + view.toString()
* + " y:" + view.getTop() + "-" + (view.getTop() +
* view.getHeight()));
*/
// me.setAction(actionresolved);
view.onTouchEvent(me);
}
if (actionresolved == MotionEvent.ACTION_MOVE) {
Log.v("tag",
"#" + actionPointerIndex + "Rawx:" + rawX + " rawy:"
+ rawY + "x:" + x + " y:" + y + " "
+ view.toString());
}
}
}
private ArrayList<View> getTouchedViews(int x, int y, int action) {
int moveGap = 0;
if (action == MotionEvent.ACTION_MOVE) {
moveGap = 0;
}
ArrayList<View> touchedViews = new ArrayList<View>();
ArrayList<View> possibleViews = new ArrayList<View>();
if (parent instanceof ViewGroup) {
possibleViews.add(parent);
for (int i = 0; i < possibleViews.size(); i++) {
View view = possibleViews.get(i);
int location[] = { 0, 0 };
view.getLocationOnScreen(location);
if (((view.getHeight() + location[1] + moveGap >= y)
& (view.getWidth() + location[0] + moveGap >= x)
& (view.getLeft() - moveGap <= x) & (view.getTop()
- moveGap <= y))
|| view instanceof FrameLayout) {
touchedViews.add(view);
possibleViews.addAll(getChildViews(view));
}
}
}
return touchedViews;
}
private ArrayList<View> getChildViews(View view) {
ArrayList<View> views = new ArrayList<View>();
if (view instanceof ViewGroup) {
ViewGroup v = ((ViewGroup) view);
if (v.getChildCount() > 0) {
for (int i = 0; i < v.getChildCount(); i++) {
views.add(v.getChildAt(i));
}
}
}
return views;
}
}
I have a game board with 5x5 squares made of canvas drawrect:
protected void onDraw(Canvas canvas) {
for (int rowNo = 0; rowNo < nSquares; rowNo++) {
paint.setColor(((rowNo & 1) == 0) ? colorA : colorB);
for (int colNo = 0; colNo < nSquares; colNo++) {
int left = colNo * squareWidth;
int top = rowNo * squareWidth;
Rect areaRect = new Rect(left, top, left + squareWidth, top + squareWidth);
canvas.drawRect(areaRect, paint);
paint.setColor((paint.getColor() == colorA) ? colorB : colorA);
paint.setTextSize((float)(squareWidth*0.8));
RectF bounds = new RectF(areaRect);
String letter = "A";
bounds.right = paint.measureText(letter, 0, letter.length());
bounds.bottom = paint.descent() - paint.ascent();
bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
canvas.drawText(letter, bounds.left, bounds.top - paint.ascent(), paint);
}
}
I want to track touch input to get the squares the user are touching..
My attempt was
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
int x = (int)event.getX();
int y = (int)event.getY();
Log.i(DEBUG_TAG, "Position: (" + x + ", " + y + ")");
int squareTouched = gameBoard.getSquare(x,y);
}
where getSquare is
public int getSquare(int x, int y) {
int row = 0;
int col = 0;
for(int rowNo = 1; rowNo <= nSquares; rowNo++) {
Log.i("Row", "Width: " + squareWidth + " rowNo: " + rowNo + " rowNo*squareW: " + rowNo*squareWidth + " y: " + y);
if(rowNo*squareWidth > y)
{
row = rowNo;
break;
}
}
for (int colNo = 1; colNo <= nSquares; colNo++) {
if(colNo*squareWidth > x)
{
col = colNo;
break;
}
}
Log.i(DEBUG_TAG, "Row: " + row + " Col: " + col);
return (row-1)*nSquares + col;
}
The problem is that the onTouchEvent getX and getY are referring to the screen 0,0, but when I draw the squares 0,0,0,0 is referring to the view origin? Am I right?
How can I get the input position relative to the game board view?
Could it be a solution to get the view position in the screen and add/subtract this to the tochEvent x- and y position?
I assume that the onDraw() and getSquare() belong to GameBoardView and onTouchEvent() to its immediate parent. If so then the onTouchEvent() should be like this
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
int x = (int)event.getX() - gameBoard.getX();
int y = (int)event.getY() - gameBoard.getY();
Log.i(DEBUG_TAG, "Position: (" + x + ", " + y + ")");
int squareTouched = gameBoard.getSquare(x, y);
}
In a View x and y in both onDraw() and onTouchEvent() is relative to the View itself (Except when the View is scrolled). Since in your case onTouchEvent() belongs to parent and onDraw() to child, I used View.getX() and getY() to translate the coordinates. View.getX() returns the x position plus translationX of the View relative to its parent.
I could not get the gameBoard().getX/Y() to return the correct values. My guess is that the action bar is excluded?
I now use getLocationOnScreen
#Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
int boardLocation[] = new int[2];
gameBoard.getLocationOnScreen(boardLocation);
int touchX = (int)event.getX();
int touchY = (int)event.getY();
int x = touchX - boardLocation[0];
int y = touchY - boardLocation[1];
int squareTouched = gameBoard.getSquare(x,y);
}
Which solved my issue..
I want to draw a line on Imageview.for example when we select a particular text the text get colored under a line.this is my code.I am not able to see the line.and how to increase the width of this line
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
imageView=(ImageView)findViewById(R.id.imageView1);
bitmap = getIntent().getExtras().getParcelable("name");
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
//bitmap1 = Bitmap.createBitmap((int) dw, (int) dh,Bitmap.Config.ARGB_8888);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.WHITE);
imageView.setImageBitmap(bitmap);
//for co-ordinate of the selected part of the image
imageView.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
x1 = (int) event.getX();
y1 = (int) event.getY();
x2 = (int) event.getX();
y2 = (int) event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
System.out.println("x1-cordinate"+x1+"y1-cordinate"+y1);
//startPt = projectXY((ImageView)v, bitmapMaster, x, y);
xstart=x1;
ystart=y1;
break;
/* case MotionEvent.ACTION_MOVE:
textSource.setText("ACTION_MOVE- " + x + " : " + y);
drawOnRectProjectedBitMap((ImageView)v, bitmapMaster, x, y);
break;*/
case MotionEvent.ACTION_UP:
System.out.println("x2-cordinate"+x2+"y2-cordinate"+y2);
canvas.drawLine(xstart, ystart, x2, y2, paint);
imageView.invalidate();
//drawOnRectProjectedBitMap((ImageView)v, bitmapMaster, x, y);
finalizeDrawing();
break;
}
/*
* Return 'true' to indicate that the event have been consumed.
* If auto-generated 'false', your code can detect ACTION_DOWN only,
* cannot detect ACTION_MOVE and ACTION_UP.
*/
return true;
}});`
I think you want something like this answer.
It will show like below
`
Button btnLoadImage;
TextView textSource, textInfo;
ImageView imageResult;
final int RQS_IMAGE1 = 1;
Uri source;
Bitmap bitmapMaster;
Canvas canvasMaster;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (Button)findViewById(R.id.loadimage);
textSource = (TextView)findViewById(R.id.sourceuri);
imageResult = (ImageView)findViewById(R.id.result);
btnLoadImage.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}});
imageResult.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
textSource.setText("ACTION_DOWN- " + x + " : " + y);
drawOnProjectedBitMap((ImageView)v, bitmapMaster, x, y);
break;
case MotionEvent.ACTION_MOVE:
textSource.setText("ACTION_MOVE- " + x + " : " + y);
drawOnProjectedBitMap((ImageView)v, bitmapMaster, x, y);
break;
case MotionEvent.ACTION_UP:
textSource.setText("ACTION_UP- " + x + " : " + y);
drawOnProjectedBitMap((ImageView)v, bitmapMaster, x, y);
break;
}
/*
* Return 'true' to indicate that the event have been consumed.
* If auto-generated 'false', your code can detect ACTION_DOWN only,
* cannot detect ACTION_MOVE and ACTION_UP.
*/
return true;
}});
}
/*
* Project position on ImageView to position on Bitmap
* draw on it
*/
private void drawOnProjectedBitMap(ImageView iv, Bitmap bm, int x, int y){
if(x<0 || y<0 || x > iv.getWidth() || y > iv.getHeight()){
//outside ImageView
return;
}else{
int projectedX = (int)((double)x * ((double)bm.getWidth()/(double)iv.getWidth()));
int projectedY = (int)((double)y * ((double)bm.getHeight()/(double)iv.getHeight()));
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(3);
canvasMaster.drawCircle(projectedX, projectedY, 5, paint);
imageResult.invalidate();
textSource.setText(x + ":" + y + "/" + iv.getWidth() + " : " + iv.getHeight() + "\n" +
projectedX + " : " + projectedY + "/" + bm.getWidth() + " : " + bm.getHeight()
);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap tempBitmap;
if(resultCode == RESULT_OK){
switch (requestCode){
case RQS_IMAGE1:
source = data.getData();
textSource.setText(source.toString());
try {
//tempBitmap is Immutable bitmap,
//cannot be passed to Canvas constructor
tempBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source));
Config config;
if(tempBitmap.getConfig() != null){
config = tempBitmap.getConfig();
}else{
config = Config.ARGB_8888;
}
//bitmapMaster is Mutable bitmap
bitmapMaster = Bitmap.createBitmap(
tempBitmap.getWidth(),
tempBitmap.getHeight(),
config);
canvasMaster = new Canvas(bitmapMaster);
canvasMaster.drawBitmap(tempBitmap, 0, 0, null);
imageResult.setImageBitmap(bitmapMaster);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
}`free draw on bitmap followed this link and now I am able to draw the line above the ImageView