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
Related
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.
public boolean onTouchEvent(MotionEvent event) {
//Log.e(Codistan_Tag, "Touch Event: " + MotionEvent.actionToString(event.getAction()));
if(isImageReady) {
if(isSelectionDragEnabled)
mPanListener.onTouchEvent(event);
if (isZoomEnabled) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
anchor_scale = mScaleFactor;
}
mScaleDetector.onTouchEvent(event);
mPanListener.onTouchEvent(event);
}
else {
switch (event.getAction()) {
case MotionEvent.ACTION_POINTER_3_DOWN:
break;
case MotionEvent.ACTION_POINTER_2_DOWN:
break;
case MotionEvent.ACTION_POINTER_1_UP:
break;
case MotionEvent.ACTION_DOWN:
if (isSelectionToolEnabled)
isDrawFinished = false;
orig_x = event.getX();
orig_y = event.getY();
//Log.e(Codistan_Tag, "-------ORIGIN-------s: " + String.valueOf(orig_x) + " " + String.valueOf(orig_y));
orig_x = (orig_x - (dest.left));
orig_y = (orig_y - (dest.top));
if(java.lang.Math.round(mScaleFactor) > 2) {
orig_x += (scale_cur_x * (riz_scale));
orig_y += (scale_cur_y * (riz_scale));
} else {
orig_x += (scale_cur_x);
orig_y += (scale_cur_y);
}
orig_x /= java.lang.Math.round(mScaleFactor);
orig_y /= java.lang.Math.round(mScaleFactor);
orig_x *= scale;
orig_y *= scale;
//mSelectionTaskManager.setOrigin((int) orig_x, (int) orig_y);
if(isSelectionToolEnabled)
MovementStack.add(new Pair((int)orig_x, (int)orig_y));
Log.e(Codistan_Tag, "Codistan Origins: " + String.valueOf(orig_x) + ", " + String.valueOf(orig_y));
break;
case MotionEvent.ACTION_MOVE:
max_dist = dist * scale;
if (event.getAction() != 1) {
move_x = event.getX();
move_y = event.getY();
//Log.e(Codistan_Tag, "Move: " + String.valueOf(move_x) + ", " + String.valueOf(move_y));
move_x = (move_x - dest.left);
move_y = (move_y - dest.top);
if(java.lang.Math.round(mScaleFactor) > 2) {
move_x += (scale_cur_x * riz_scale);
move_y += (scale_cur_y * riz_scale);
} else {
move_x += (scale_cur_x);
move_y += (scale_cur_y);
}
move_x /= java.lang.Math.round(mScaleFactor);
move_y /= java.lang.Math.round(mScaleFactor);
move_x *= scale;
move_y *= scale;
Log.e(Codistan_Tag, "Codistan Move: " + String.valueOf(move_x) + ", " + String.valueOf(move_y));
if (move_x >= 0 && move_y >= 0) {
if (!isSelectionToolEnabled && isDistortionEnabled) {
warpPhotoFromC(image, height, width, max_dist/mScaleFactor, orig_x, orig_y, move_x, move_y);
first++;
distortedBmp.setPixels(image, 0, width, 0, 0, width, height);
fg = false;
} else {
//Cut Tool Enabled
distortedBmp.setPixels(image, 0, width, 0, 0, width, height);
MovementStack.add(new Pair((int) move_x, (int) move_y));
}
}
}
orig_x = move_x;
orig_y = move_y;
break;
case MotionEvent.ACTION_UP:
if (isSelectionToolEnabled)
isDrawFinished = true;
break;
}
}
v.invalidate();
}
return true;
}
basically m taking the screen shot and applying cropping on it i m selecting the cropping area using finger to draw a portion to crop . when i left moving my finger then the line appear but i want the line to follow my finger
Create a customView over which you can draw the line.As it appears that this view should appear above your image then better extend it with Framelayout with same .And place it above image.
FingerLine.class
public class FingerLine extends FrameLayout {
private final Paint mPaint;
private float startX;
private float startY;
private float endX;
private float endY;
public FingerLine(Context context) {
this(context, null);
}
public FingerLine(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setColor(Color.RED);
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(startX, startY, endX, endY, mPaint);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_UP:
endX = event.getX();
endY = event.getY();
invalidate();
break;
}
return true;
}
}
Note:Don't forget to call invalidate() because it will be responsible to call onDraw
This code loads a picture and puts it in a imageView , then you can draw rectangles on the image, using the canvas.
imageView there are two , one for loading an image , the other to draw rectangles on this . I need to zoom and pan (using two fingers for both) in the image and drawing at the same time , can anyone help me ?
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;
#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' 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;
}
});
}
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 (3);
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 ());
}
}
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 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);
//Create bitmap of same size for drawing
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;
}
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/loadimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image 1" />
<TextView
android:id="#+id/sourceuri"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#android:color/background_dark"
android:scaleType="centerInside" />
<ImageView
android:id="#+id/drawingpane"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_alignLeft="#id/result"
android:layout_alignTop="#id/result"
android:layout_alignRight="#id/result"
android:layout_alignBottom="#id/result"/>
</RelativeLayout>
</LinearLayout>
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;
}
});
So I'm attempting to make a "magnetic poetry" type application. Users will move various Button widgets on the screen. I am using a Button widget since it is the closest to the look of the magnet, though I am open to other options!
The objects are not properly moving with my finger. They're close but they're not exactly in line with my finger. The X coordinate on my phone seems to be fine, but the Y corrdinate is off. Is this perhaps due to the title bar?
private final static int DRAGGING_OFF = 0;
private final static int DRAGGING_ON = 1;
private int dragStatus;
private GestureDetector mGestureDetector;
private int mOffsetX;
private int mOffsetY;
private LayoutParams mOldParams;
private RelativeLayout.LayoutParams lp;
#Override
public boolean onTouchEvent(MotionEvent event) {
if(!mGestureDetector.onTouchEvent(event)) {
if(event.getAction() == MotionEvent.ACTION_MOVE) {
if(dragStatus == DRAGGING_ON) {
Log.e(VIEW_LOG_TAG, "Dragging! RAW -- " + event.getRawX() + " : " + event.getRawY() + " NOT RAW -- " + event.getX() + " : " + event.getY());
int rawX, rawY;
int finalX, finalY;
rawX = (int) event.getRawX();
rawY = (int) event.getRawY();
finalX = rawX - mOffsetX;
finalY = rawY - mOffsetY;
lp.setMargins(finalX, finalY, 0, 0);
this.setLayoutParams(lp);
}
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) {
if(dragStatus == DRAGGING_ON) {
dragStatus = DRAGGING_OFF;
Log.e(VIEW_LOG_TAG, "Stopped dragging!");
}
return true;
} else {
return super.onTouchEvent(event);
}
} else {
return true;
}
}
private final GestureDetector.SimpleOnGestureListener mListener = new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDown(MotionEvent e) {
int[] location = new int[2];
Log.e(VIEW_LOG_TAG, "Down! RAW -- " + e.getRawX() + " : " + e.getRawY() + " NOT RAW -- " + e.getX() + " : " + e.getY());
dragStatus = DRAGGING_ON;
// Sets the current location of the View in the int[] passed to it; x then y.
getLocationInWindow(location);
Log.e(VIEW_LOG_TAG, "Down location: " + location[0] + " " + location[1]);
mOffsetX = (int) e.getRawX() - location[0];
mOffsetY = (int) e.getRawY() - location[1];
mOldParams = getLayoutParams();
return true;
}
};
I think the issue is that you're not getting the DELTA of the current touch point Y and the cached, last touch point y. You need something like this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.text);
final ImageView image = (ImageView) findViewById(R.id.image);
matrix.setTranslate(1f, 1f);
image.setImageMatrix(matrix);
image.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
matrix.getValues(m); //copy matrix values into array
PointF currentXYTouchPoint = new PointF(event.getX(), event.getY());
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN: //start of pressed gesture
lastXYTouchPoint.set(event.getX(), event.getY()); //save the last touchpoint
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
//calculate the change in finger position
float deltaX = currentXYTouchPoint.x - lastXYTouchPoint.x;
float deltaY = currentXYTouchPoint.y - lastXYTouchPoint.y;
matrix.postTranslate(deltaX, deltaY); //move the entire image by the deltas
image.setImageMatrix(matrix);
// save this last starting touchpoint
lastXYTouchPoint.set(currentXYTouchPoint.x, currentXYTouchPoint.y);
break;
}
textView.setText("TouchPoint started at " + currentXYTouchPoint.x + ", " + currentXYTouchPoint.y + " & the matrix is now " + Arrays.toString(m));
return true;
}
});
}
Adapt it to your own purposes, but the basic idea is there.