Bitmap from ImageView after onTouch - android

I have an imageview, and after i add image (a marker) on this imageview.
At the end, i want to create a bitmap, included the new marker.
But if i try to create a bitmap from relative layout, i create an image without new marker! Why?
imageview= (ImageView)findViewById(R.id.image);
//insert a marker on my imageview
final RelativeLayout rr = (RelativeLayout) findViewById(R.id.relative);
rr.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() ;
int y = (int) event.getY();
RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
ImageView iv=new ImageView(getApplicationContext());
lp.setMargins(x,y,0,0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(R.drawable.marker));
((ViewGroup)v).addView(iv);
//create a bitmap from relative layout but the new bitmap is without marker
Bitmap b1 = Bitmap.createBitmap(rr.getWidth(), rr.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b1);
((ViewGroup)v).draw(c);
}
return false;
}

It happens because adding marker dynamically to the layout, to add dynamic views it has some delay. Thats the reason creating bitmap without marker. On second touch with singe marker bitmap will be created. The solution is save bitmap after some delay.
Solution is here:
private Handler handler = new Handler(); //handler object in global
rr.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() ;
int y = (int) event.getY();
RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
ImageView iv=new ImageView(getApplicationContext());
lp.setMargins(x,y,0,0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(R.drawable.marker));
((ViewGroup)v).addView(iv);
//run handler after 1000 milli seconds i.e 1 sec
handler.postDelayed(runnable, 1000);
}
return false;
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
//wrote your block of code here
//create a bitmap from relative layout but the new bitmap is without marker
Bitmap b1 = Bitmap.createBitmap(rr.getWidth(), rr.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b1);
((ViewGroup)v).draw(c);
}
};
Look here How to Save Bitmap as image in SD card

Related

How to move Image (inside a Imageview) corresponding to touch pointer?

I'm new to building apps on Android. I do have Java and android studio working experience, and build basic android apps but the project I'm working on now is a little bit complicated.
I want to move a image inside a imageview corresponding to touch pointer, in other words to direction of touch but inside a specific area(circular).
Just like in android app pou i.e. pou eyes move corresponding to touch pointer.
I started with below code:
public class TouchActivity extends Activity {
private ViewGroup mainLayout;
private ImageView image;
private int xDelta;
private int yDelta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch);
mainLayout = (RelativeLayout) findViewById(R.id.main);
image = (ImageView) findViewById(R.id.image);
image.setOnTouchListener(onTouchListener());
}
private OnTouchListener onTouchListener() {
return new OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent event) {
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
view.getLayoutParams();
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
Toast.makeText(TouchActivity.this,
"thanks for new location!", Toast.LENGTH_SHORT)
.show();
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = x - xDelta;
layoutParams.topMargin = y - yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
mainLayout.invalidate();
return true;
}
};
}
}
... and successfully managed to move an image corresponding to touch pointer but I want to implement something like this:
(eyes are moving according to touch but inside a specific area)
Any ideas?
(by kalu) Move click image inside imageview ajust height or with depends the size of resource(image) and translate x or y direction.
Try This:
// your image view
ImageView mCoverView = findViewById(R.id.imageview);
Glide.with(aActivity).load(cover) //set img url
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(new BitmapImageViewTarget(mCoverView) {
#Override
protected void setResource(Bitmap resource) {
final Bitmap f_res = resource;
// just if you want change for a drawable res
// final Bitmap f_res = BitmapFactory.decodeResource(aActivity.getResources(),R.drawable.ic_ampliada);
//k ajust center but ajust height or with depend the image
mCoverView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mCoverView.setImageBitmap(f_res);
final String dir;
if(f_res.getWidth()>f_res.getHeight())
dir="x";
else
dir="y";
mCoverView.setOnClickListener(new View.OnClickListener() {
// size of move
int value = 25;
double resh=f_res.getHeight();
double resw=f_res.getWidth();
double coverh =mCoverView.getHeight();
double coverw = mCoverView.getWidth();
int xTranslate = 0;
double sacale_w_from_h = coverh / resh * resw;
//k wtotal distancia do centro as bordas (x=0 (centro imagem))
double wtotal = (sacale_w_from_h/2);
int yTranslate = 0;
double sacale_h_from_w = coverw / resw * resh;
//k wtotal distancia do centro as bordas (y=0 (centro imagem))
double htotal = sacale_h_from_w / 2;
#Override
public void onClick(View v) {
if (dir == "x"){
if (xTranslate>wtotal || xTranslate<-wtotal)
value=-value;
xTranslate += value;
}else if(dir == "y"){
if (yTranslate>htotal || yTranslate<-htotal)
value=-value;
yTranslate += value;
}
this.translateImage(xTranslate,yTranslate);
}
private void translateImage(int xTranslate, int yTranslate)
{
Bitmap translateBitmap = Bitmap.createBitmap(f_res.getWidth() + xTranslate, f_res.getHeight() + yTranslate, f_res.getConfig());
Canvas translateCanvas = new Canvas(translateBitmap);
Matrix translateMatrix = new Matrix();
translateMatrix.setTranslate(xTranslate, yTranslate);
Paint paint = new Paint();
translateCanvas.drawBitmap(f_res, translateMatrix, paint);
mCoverView.setImageBitmap(translateBitmap);
}
});
}
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
if (glideAnimation == null || !glideAnimation.animate(resource, this)) {
setResource(resource);
}
}
});
//-------------------------------------------------------------------

How to keep ball moving

I'm trying to create a simple app with a ball moving around reflecting off the screen edges.
I've found out how to create my ball. However i'm not able to move it around.
Here's my code till now.
protected void onCreate(Bundle savedInstanceState) {
initial_x=100;
initial_y=100;
speed_x=1;
speed_y=1;
x=initial_x;
y=initial_y;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
draw();
}
private void draw() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
Log.d("dimensions",String.valueOf(width));
Log.d("dimensions",String.valueOf(height));
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
g = new Canvas(bitmap);
g.drawColor(Color.WHITE);
paint = new Paint();
paint.setColor(Color.RED);
g.drawCircle(50,50, 20, paint); //Put your values
// In order to display this image, we need to create a new ImageView that we can display.
ImageView imageView = new ImageView(this);
// Set this ImageView's bitmap to ours
imageView.setImageBitmap(bitmap);
// Create a simple layout and add imageview to it.
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
// Show layout in activity.
setContentView(layout);
layout.setOnClickListener(l);
}
I've set an onclick listener to basically be able to move the ball when i touch the screen. How do I make this a continuous process?
Edit:
I changed the onclicklistener to an ontouchlistener to keep the ball moving while i touch the screen but it still works like an onclick listener. here is the code
OnTouchListener l = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
g.drawColor(Color.WHITE);
x+=speed_x;
y+=speed_y;
g.drawCircle(x, y, 20, paint);
if(x==0)
speed_x=-1;
if(x==height)
speed_x=1;
if(y==0)
speed_y=-1;
if(y==width)
speed_y=1;
v.invalidate();
break;
}
return false;
}
};
Use a TimerTask to periodically update the position continuously. Probably 10 to 30 times a second should suffice.
Put your drawing and position update logic in the run() method of TimerTask since creating another thread won't work. (Drawing must occur on GUI thread).
Hope this helps.
Edit:
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
// Update logic here
runOnUiThread(new Runnable() {
#Override
public void run() {
// Drawing logic here
}
});
}
}
Timer timer = new Timer();
timer.schedule(myTimerTask, 50, 50);

how can we change image view background on swipe?

As a example,have to draw a layout of images.
I inflated an ImageView into a layout. When I swipe on the screen I need to change the color of the each circle to green. How should I do it. I tried with gesture detector, but I can't get what I need.
and this is my code.. I create this view by inflating an image view..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(1024);
setContentView(R.layout.test);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
count = width/30;
totalCircles = count * (height/30);
horizontalSpace = width%30;
verticalSpace = height%30;
mRelativeLayout = (RelativeLayout)findViewById(R.id.fl);
mRelativeLayout.setPadding(horizontalSpace/2, verticalSpace/2, horizontalSpace/2, verticalSpace/2);
for(int i=1;i<totalCircles+1;i++){
myButton = new ImageView(this);
myButton.setId(i);
myButton.setImageResource(R.drawable.circle_grey);
LayoutParams lp = new LayoutParams(0,0);
if(i%count != 1){
lp.addRule(RelativeLayout.RIGHT_OF, imgViews.get(i-2).getId());
if(imView != null){
lp.addRule(RelativeLayout.BELOW, imView.getId());
}
if(i%count == 0){
imView = myButton;
}
}else{
if(imView != null){
lp.addRule(RelativeLayout.BELOW, imView.getId());
}
}
mRelativeLayout.addView(myButton,lp);
myButton.getLayoutParams().width = 30;
myButton.getLayoutParams().height = 30;
imgViews.add(myButton);
myButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
System.out.println("Inside touch listener");
ImageView imV = (ImageView)v;
imV.setImageResource(R.drawable.circle_green);
}
return false;
}
});
}
}
Jack K Fouani's answer is partially correct. Instead of imagView.onTouch you need to use gridview.onTouch.
Please check this sample.
gv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
float currentXPosition = event.getX();
float currentYPosition = event.getY();
int position = gv.pointToPosition((int)currentXPosition, (int) currentYPosition);
//using the position obtained you can change the imageview color.
}
return true;
}
});
Instead of inflating one ImageView. You should fill a GridView where every GridCell contains a circle image. Now
set the OnTouchEvent of those Gridcells to change the ImageView within the GridCell.
my advice is to use GrideView with adapter , inside the adapter you will have position for each imagView the position allow you to check if image is touched or not depending on that you can change ImageView color to white or green

android, add multiple ImageViews onTouch event

I've just started programming for Android. I've searched for my problem a lot, but the advises didn't help me. I want the same images appear on screen in the touch coordinates. That's what I've done:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View main_view = (View)findViewById(R.id.main_view);
main_view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView image = new ImageView(getApplicationContext());
//ImageView image = (ImageView)findViewById(R.id.broken);
image.setImageResource(R.drawable.broken);
image.setX(event.getX() + image.getWidth() / 2);
image.setY(event.getY() - image.getHeight() / 2);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
image.setLayoutParams(p);
top_layout.addView(image);
return true;
}
});
}
Everything seems right to me, but when touching the screen, nothing happens. Where is the obvious mistake I've made? Thanks in advance.
You can't do that in a LinearLayout.
Let's use a FrameLayout instead.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
MainActivity.java
public class MainActivity extends Activity {
private FrameLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (FrameLayout) findViewById(R.id.framelayout);
mLayout.setOnTouchListener(mListener);
}
private OnTouchListener mListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
// decode the resource to get width and height
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, opts);
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
// set the imageview's top and left margins
FrameLayout.LayoutParams lp = new LayoutParams(imageWidth, imageHeight);
lp.leftMargin = (int) (event.getX() - (imageWidth / 2));
lp.topMargin = (int) (event.getY() - (imageHeight / 2));
ImageView image = new ImageView(MainActivity.this);
image.setImageResource(R.drawable.ic_launcher);
mLayout.addView(image, lp);
return false;
}
return false;
}
};
}
setX and setY don't set the images position. It basically scrolls the image in place. The position is controlled by its parent view. Since its parent is a linear layout, it will always be placed below or to the right of the thing above it in the layout. If you want to place it somewhere exactly, you need to put it in a parent that supports that, such as the deprecated AbsoluteLayout.

Add ImageView to FingerPaint View

I've created fingerpaint app. from finger paint android example API.
(SAMPLE: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.2_r1.1/com/example/android/apis/graphics/FingerPaint.java)
Now i've created an function to create a bitmap from paint (and move). This is my code:
public void addProgrammatlyImage(int pos[], String filePath){
// Let's create the missing ImageView
ImageView image = new ImageView(this);
// Now the layout parameters, these are a little tricky at first
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
image.setScaleType(ImageView.ScaleType.MATRIX);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
image.setImageBitmap(selectedImage);
image.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
System.out.println("TOUCH!!");
switch(event.getActionMasked())
{
case MotionEvent.ACTION_DOWN:
offset_x = (int)event.getX();
offset_y = (int)event.getY();
selected_item = v;
break;
default:
break;
}
return false;
}
});
// Let's get the root layout and add our ImageView
FrameLayout layout = (FrameLayout) findViewById(R.id.vg1);
layout.setBackgroundColor(getResources().getColor(R.color.xxx));
layout.bringToFront();
((FrameLayout) layout).addView(image, 0, params);
}
My problem is:
if inflate the new image on the same level of fingerpaint view (MyView class in the sample), disappear on the background (fingerpaint is in front of the image).
i'm unable to insert image as child of MyView. In this case there is a problem when inflate the image: classcast exception, can't cast view (MyViewClass) to ViewGroup.
Can you help me please??

Categories

Resources