Animate ImageView's Bitmap Position - android

I have an ImageView with width = 1080 and height = 1920
I have a bitmap with width = 3340 and height = 1920
I set the scale type of the imageView to MATRIX. So that the bitmap is not scaled to the imageView
imageView.setScaleType(ImageView.ScaleType.MATRIX);
I would like to animate the bitmap from left to right and vice versa.
Is it possible to be done? Any thoughts?

please create following Custom view class into your project
package com.company.xyz;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
/**
* Created by rohitp on 12/10/2015.
*/
public class CustomImageView extends View {
Bitmap bm;
int x, y;
boolean flag = true;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
try{
int src_resource = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);
bm = getDrawable(getResources(),src_resource);
}catch (Exception e){
}
}
public static Bitmap getDrawable(Resources res, int id){
return BitmapFactory.decodeResource(res, id);
}
public void setBm(Bitmap bm) {
this.bm = bm;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if(bm != null){
if(flag){
if (x < (getMeasuredWidth()-bm.getWidth())) {
x += 10;
Log.e("Custom",x+""+getMeasuredWidth());
}
else {
Log.e("Custom",x+" false");
flag = false;
}
}else{
if (x >0 ) {
x -= 10;
Log.e("Custom",x+" -");
}
else {
flag = true;
Log.e("Custom",x+" true");
}
}
canvas.drawBitmap(bm, x, y, new Paint());
}
invalidate();//calls this method again and again
}
}
create an layout xml with following
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.company.xyz.CustomImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/animate_pic"
android:src="#drawable/test">
</com.company.xyz.CustomImageView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And you can also change bitmap through code at runtime
((CustomImageView) findViewById(R.id.animate_pic)).setBm(bm)

As per an example in this link http://www.sanfoundry.com/java-android-program-animante-bitmap/ you need to move the image using canvas inside onDraw(). So, follow this link, may be this will help you. And let me know for any issues.

Related

Android - CustomView - java.lang.IllegalStateException: Surface was not locked

I'm trying to draw a rectangle over camera2 textureview, when i run the code I see the usual camera screen with moving square , and when I Click (touch) it, app crashes with the error in topic. I also not sure I implemented the custom view correctly, Here are all the relevant parts, Would love some help (I'm not sure I have a good layout xml, I added ViewGroup code under OnCrearte, not sure i even need to touch xml)
-------CameraActivity.java:
package com.example.android.camera2video;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;
public class CameraActivity extends Activity {
private Context context;
CustomView customview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
customview = new CustomView(this);
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
viewGroup.addView(new CustomView(this));
if (null == savedInstanceState) {
getFragmentManager().beginTransaction()
.replace(R.id.container, Camera2VideoFragment.newInstance())
.commit();
}
}
}
-------CustomView.java
package com.example.android.camera2video;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CustomView extends SurfaceView {
private Paint paint;
private SurfaceHolder mHolder;
private Context context;
public CustomView(Context context) {
super(context);
mHolder = getHolder();
mHolder.setFormat(PixelFormat.TRANSPARENT);
this.context = context;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// real work here
}
private void doAdditionalConstructorWork() {
// init variables etc.
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
invalidate();
if (mHolder.getSurface().isValid()) {
final Canvas canvas = mHolder.lockCanvas();
Log.d("touch", "touchRecieved by camera");
System.err.println("EXIT 1");
if (canvas != null) {
Log.d("touch", "touchRecieved CANVAS STILL Not Null");
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawColor(Color.TRANSPARENT);
canvas.drawCircle(event.getX(), event.getY(), 100, paint);
mHolder.unlockCanvasAndPost(canvas);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Canvas canvas1 = mHolder.lockCanvas();
if(canvas1 !=null){
canvas1.drawColor(0, PorterDuff.Mode.CLEAR);
mHolder.unlockCanvasAndPost(canvas1);
}
}
}, 1000);
}
mHolder.unlockCanvasAndPost(canvas);
}
}
return false;
}
}
-----fragment_camera2_video.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.android.camera2video.AutoFitTextureView
android:id="#+id/texture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_below="#id/texture"
android:background="#4285f4">
<Button
android:id="#+id/video"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/record" />
<ImageButton
android:id="#+id/info"
android:contentDescription="#string/description_info"
style="#android:style/Widget.Material.Light.Button.Borderless"
android:layout_width="4dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:padding="20dp"
android:src="#drawable/ic_action_info" />
</FrameLayout>
</RelativeLayout>
Only one thing can be drawing to a View at a time; once the SurfaceView is connected to the camera, you're not able to lock it for drawing yourself.
Your crash is probably because you're calling mHolder.unlockCanvasAndPost(canvas); outside of the null check.
If you want to draw over the cameara preview, you need a second View positioned on top of the SurfaceView.

Android: Draw text on ImageView with finger touch

i completed the drawing text on ImageView and i saved the final image in sd card. My problem is, when i am touching the screen to draw the text, my image in the ImageView is disappearing.
Code
import java.io.File;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class DrawTextOnImgActivity extends Activity {
private Button btn_save, btn_resume;
private ImageView iv_canvas;
private Bitmap baseBitmap;
private Canvas canvas;
private Paint paint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_text_on_img);
// The initialization of a brush, brush width is 5, color is red
paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
iv_canvas = (ImageView) findViewById(R.id.imageView1);
btn_save = (Button) findViewById(R.id.btn_save);
btn_resume = (Button) findViewById(R.id.btn_resume);
btn_save.setOnClickListener(click);
btn_resume.setOnClickListener(click);
iv_canvas.setOnTouchListener(touch);
}
private View.OnTouchListener touch = new OnTouchListener() {
// Coordinate definition finger touch
float startX;
float startY;
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// Press the user action
case MotionEvent.ACTION_DOWN:
// The first drawing initializes the memory image, specify the background is white
if (baseBitmap == null) {
baseBitmap = Bitmap.createBitmap(iv_canvas.getWidth(),
iv_canvas.getHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
}
// Recording began to touch point coordinate
startX = event.getX();
startY = event.getY();
break;
// The user's finger on the screen of mobile action
case MotionEvent.ACTION_MOVE:
// Record the coordinates of the mobile point
float stopX = event.getX();
float stopY = event.getY();
//According to the coordinates of the two points, drawing lines
canvas.drawLine(startX, startY, stopX, stopY, paint);
// Update start point
startX = event.getX();
startY = event.getY();
// The pictures to the ImageView
iv_canvas.setImageBitmap(baseBitmap);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;
}
};
private View.OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
saveBitmap();
break;
case R.id.btn_resume:
resumeCanvas();
break;
default:
break;
}
}
};
/**
* Save the image to the SD card.
*/
protected void saveBitmap() {
try {
// Save the image to the SD card.
File folder = new File(Environment.getExternalStorageDirectory() + "/DrawTextOnImg");
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(Environment.getExternalStorageDirectory()+"/DrawTextOnImg/tempImg.png");
FileOutputStream stream = new FileOutputStream(file);
baseBitmap.compress(CompressFormat.PNG, 100, stream);
Toast.makeText(DrawTextOnImgActivity.this, "Save the picture of success", Toast.LENGTH_SHORT).show();
// Android equipment Gallery application will only at boot time scanning system folder
// The simulation of a media loading broadcast, for the preservation of images can be viewed in Gallery
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
} catch (Exception e) {
Toast.makeText(DrawTextOnImgActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
/**
* Clear the drawing board
*/
protected void resumeCanvas() {
// Manually clear the drawing board, to create a drawing board
if (baseBitmap != null) {
baseBitmap = Bitmap.createBitmap(iv_canvas.getWidth(), iv_canvas.getHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
iv_canvas.setImageBitmap(baseBitmap);
Toast.makeText(DrawTextOnImgActivity.this, "Clear the drawing board, can be re started drawing", Toast.LENGTH_SHORT).show();
}
}
}
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />
By using this code i am writing the text on ImageView but image in the ImageView is disappearing. So, please help me to write the text on image of ImageView
I achieved it by fallowing this code
DrawTextOnImgActivity
import java.io.File;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
public class DrawTextOnImgActivity extends Activity {
ImageView ivDrawImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_text_on_img);
ivDrawImg = (ImageView) findViewById(R.id.iv_draw);
Button btnSave = (Button) findViewById(R.id.btn_save);
Button btnResume = (Button) findViewById(R.id.btn_resume);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveImg();
}
});
btnResume.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void saveImg(){
Bitmap image = Bitmap.createBitmap(ivDrawImg.getWidth(), ivDrawImg.getHeight(), Bitmap.Config.RGB_565);
ivDrawImg.draw(new Canvas(image));
String uri = Images.Media.insertImage(getContentResolver(), image, "title", null);
Log.e("uri", uri);
try {
// Save the image to the SD card.
File folder = new File(Environment.getExternalStorageDirectory() + "/DrawTextOnImg");
if (!folder.exists()) {
folder.mkdir();
//folder.mkdirs(); //For creating multiple directories
}
File file = new File(Environment.getExternalStorageDirectory()+"/DrawTextOnImg/tempImg.png");
FileOutputStream stream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, stream);
Toast.makeText(DrawTextOnImgActivity.this, "Picture saved", Toast.LENGTH_SHORT).show();
// Android equipment Gallery application will only at boot time scanning system folder
// The simulation of a media loading broadcast, for the preservation of images can be viewed in Gallery
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);*/
} catch (Exception e) {
Toast.makeText(DrawTextOnImgActivity.this, "Save failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
DrawView
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
public class DrawView extends ImageView {
private int color = Color.parseColor("#0000FF");
private float width = 4f;
private List<Holder> holderList = new ArrayList<Holder>();
private class Holder {
Path path;
Paint paint;
Holder(int color, float width) {
path = new Path();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(width);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
}
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
holderList.add(new Holder(color, width));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Holder holder : holderList) {
canvas.drawPath(holder.path, holder.paint);
}
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
holderList.add(new Holder(color,width));
holderList.get(holderList.size() - 1).path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
holderList.get(holderList.size() - 1).path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
public void resetPaths() {
for (Holder holder : holderList) {
holder.path.reset();
}
invalidate();
}
public void setBrushColor(int color) {
this.color = color;
}
public void setWidth(float width) {
this.width = width;
}
}
Layout (activity_draw_text_on_img)
<RelativeLayout 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:background="#FFFFFF" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<com.app.drawtextonimg.DrawView
android:id="#+id/iv_draw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:src="#drawable/rajamouli" />
</RelativeLayout>
<Button
android:id="#+id/btn_save"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:background="#000000"
android:text="#string/save"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_resume"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#000000"
android:text="#string/resume"
android:textColor="#FFFFFF" />
</RelativeLayout>
Manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Project link
If I understand your question correctly, I think that you should remove this line from your Case.ACTION_MOVE.
iv_canvas.setImageBitmap(baseBitmap);
By doing this you are resetting your ImageView every time you move on the screen which will cause the ImageView to be just a blank

How to capture part of a ScrollView as its content is scrolling?

After extending the ScrollView class I was able to easily be notified of the scrolling in realtime.
Now I need to capture the content of this scrollview in a very specific part.
Let's say I want to capture the top of the screen (matching parent width and a defined height, like 100dp). But only the content of the ScrollView and not the rest, if there is anything else on the top but not as part of the ScrollView.
I tried using on the scrollview :
setDrawingCacheEnabled(true);
getDrawingCache(true);
setDrawingCacheEnabled(false);
Then I tried to crop so that I get the part I want :
Bitmap.createBitmap(complete, 0, 0, width, height);
Results are very far from what I want to achieve and performance are very very poor and at some point I would get either a SIGENV or getDrawingCache(true) tries to use a recycled bitmap...
So how can I easily capture the content in the desired area without too much performance hit ?
Note: this process must be done as I am scrolling the content, so inside ScrollView's onScrollChanged(final int x, final int y).
Thanks !
Since the problem was fun I implemented it, it seems to work fine. I guess that you are recreating a Bitmap each time that's why goes slow.
The idea is like this, you create an area in the ScrollView that you want to copy (see Rect cropRect and Bitmap screenshotBitmap), it's full width and you just need to set the height. The view automatically set a scroll listener on itself and on every scroll it will copy that area. Note that setDrawingCacheEanbled(true) is called just once when the view is instantiated, it basically tells the view that you will call getDrawingCache(), which will return the Bitmap on which the view is drawing itself. It then copy the area of interest on screenshotBitmap and that's the Bitmap that you might want to use.
ScreenshottableScrollView.java
package com.example.lelloman.screenshottablescrollview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;
/**
* Created by lelloman on 16-2-16.
*/
public class ScreenshottableScrollView extends ScrollView implements ViewTreeObserver.OnScrollChangedListener {
public interface OnNewScreenshotListener {
void onNewScreenshot(Bitmap bitmap);
}
private Bitmap screenshotBitmap = null;
private Canvas screenshotCanvas = null;
private int screenshotHeightPx = 0;
private OnNewScreenshotListener listener = null;
private Rect cropRect;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public ScreenshottableScrollView(Context context) {
super(context);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
setDrawingCacheEnabled(true);
getViewTreeObserver().addOnScrollChangedListener(this);
}
public void setOnNewScreenshotListener(OnNewScreenshotListener listener){
this.listener = listener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if(screenshotHeightPx != 0)
makeScrenshotBitmap(w,h);
}
public void setScreenshotHeightPx(int q){
screenshotHeightPx = q;
makeScrenshotBitmap(getWidth(), getHeight());
}
private void makeScrenshotBitmap(int width, int height){
if(screenshotBitmap != null) screenshotBitmap.recycle();
if(width == 0 || height == 0) return;
screenshotBitmap = Bitmap.createBitmap(width, screenshotHeightPx, Bitmap.Config.ARGB_8888);
screenshotCanvas = new Canvas(screenshotBitmap);
cropRect = new Rect(0,0,width,screenshotHeightPx);
}
#Override
public void onScrollChanged() {
if(listener == null) return;
Bitmap bitmap = getDrawingCache();
screenshotCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
screenshotCanvas.drawBitmap(bitmap,cropRect, cropRect,paint);
listener.onNewScreenshot(screenshotBitmap);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.lelloman.screenshottablescrollview.MainActivity">
<com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView
android:id="#+id/scrollView"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView>
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ff000000"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="100dp" />
</LinearLayout>
MainActivity.java
package com.example.lelloman.screenshottablescrollview;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringBuilder builder = new StringBuilder();
Random random = new Random();
String AB = "abcdefghijklmnopqrstuvwxyz ";
for(int i=0;i<100;i++){
builder.append("\n\n"+Integer.toString(i)+"\n\n");
for(int j =0;j<1000;j++){
builder.append(AB.charAt(random.nextInt(AB.length())));
}
}
((TextView) findViewById(R.id.textView)).setText(builder.toString());
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
ScreenshottableScrollView scrollView = (ScreenshottableScrollView) findViewById(R.id.scrollView);
scrollView.setScreenshotHeightPx((int) (getResources().getDisplayMetrics().density * 100));
scrollView.setOnNewScreenshotListener(new ScreenshottableScrollView.OnNewScreenshotListener() {
#Override
public void onNewScreenshot(Bitmap bitmap) {
Log.d("MainActivity","onNewScreenshot");
imageView.setImageBitmap(bitmap);
}
});
}
}

How to Draw something with your finger in an Android App.... And save it to the web

**THIS QUESTION WAS SUCCESSFULLY ANSWERED AND HAS BECOME A BLOG POST <- click **
Hi I am a PHP developer I want to do a simple thing - I want to draw something drawn on a blank page on an Android Phone (with a finger with a largeish "emulated pen nib") and store the bitmap as a jpeg on a server by http post.
Here is what I have so far but this is taken from a tutorial that is involved with writing sprites for a game.. And I cant' adapt it
package com.my.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class DrawCapture extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.draw_capture);
v = new OurView(this);
v.setOnTouchListener(this);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
x = y = 0;
setContentView(v);
}
#Override
protected void onPause(){
super.onPause();
v.pause();
}
protected void onResume(){
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOK = false;
public OurView(Context context) {
super(context);
holder = getHolder();
}
public void run() {
while (isItOK == true){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
//perform canvas drawing
if (!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
onDraw(c);
holder.unlockCanvasAndPost(c);
}
}
public void onDraw(Canvas c){
c.drawARGB(255, 210, 210, 210);
c.drawBitmap(ball, x - (ball.getWidth()/2), y - (ball.getHeight()/2), null);
}
public void pause(){
isItOK = false;
while(true){
try{
t.join();
} catch(InterruptedException e){
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOK = true;
t = new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent me){
switch (me.getAction()){
case MotionEvent.ACTION_DOWN :
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP :
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_MOVE :
x = me.getX();
y = me.getY();
break;
}
return true;
}
}
and here is the XML
<?xml version="1.0" encoding="utf-8"?>
<SurfaceView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</SurfaceView>
Can someone please help me? I feel I am close - I use the blueball as a pen nib I just want to "save" this and possibly I'll need to have a button (or menu) on the XML page to do this ? I know it's a bit of a beg but there are a lot of people online asking how to draw with your finger and save something to the "cloud" if people could respond with examples of the code (not references) I promise I will compile this into a proper tutorial piece of code for the eventual benefit of all. Including the PHP server side code that I already am really happy with.
You can try to use the Gesture Object proposed by Google, try to execute my following code :
Activity1 xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<android.gesture.GestureOverlayView
android:id="#+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadeEnabled="false"
android:fadeOffset="5000000000"
android:gestureColor="#000000"
android:gestureStrokeType="multiple"
android:gestureStrokeWidth="1"
android:uncertainGestureColor="#000000"
android:layout_above="#+id/save_button" />
<Button
android:id="#id/save_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20sp"
android:paddingLeft="20sp"
android:paddingRight="20sp"
android:text="Save"
android:textSize="22sp" />
</RelativeLayout>
Activity1 java :
package com.testandroidproject;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Activity1 extends Activity {
private Button button_save;
private GestureOverlayView gesture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gesture = (GestureOverlayView) findViewById(R.id.gestures);
button_save = (Button) findViewById(R.id.save_button);
button_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
Bitmap gestureImg = gesture.getGesture().toBitmap(100, 100,
8, Color.BLACK);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gestureImg.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("draw", bArray);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Activity1.this, "No draw on the string",
3000).show();
}
}
});
}
}
Activity2 xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<ImageView
android:id="#+id/image_saved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Activity2 java :
package com.testandroidproject;
import java.io.ByteArrayInputStream;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_image);
ImageView image = (ImageView) findViewById(R.id.image_saved);
ByteArrayInputStream imageStreamClient = new ByteArrayInputStream(
getIntent().getExtras().getByteArray("draw"));
image.setImageBitmap(BitmapFactory.decodeStream(imageStreamClient));
}
}
Hope you will find this helpful.
I'm not sure what part of the "save" you are trying to accomplish, but I'll assume you're asking how to store what you've drawn on the canvas to a bitmap.
First, make yourself a bitmap to draw into. Say, canvasBitmap. Then:
c.setBitmap(canvasBitmap);
This will store everything that has been drawn into 'canvasBitmap.' Then, when the user presses a button to save:
savedBitmap = Bitmap.copy(canvasBitmap.getConfig(), true);
Now, take savedBitmap and fire it off into the cloud. Hope that helps.

How to draw lines over ImageView on Android?

I am trying to develop a simple map application, which will display a map in the screen.
When the user moves the cursor on screen, I want to display 2 perpendicular lines over my map. I had tried many examples to get an idea for that, but unfortunately, didn't succeed.
How can I make this?
And as one previous questionhere I had tried. but didn't get the answer. Can anyone guide me?
My main.xml is as following:
<?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" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="#+id/main_imagemap"
android:src="#drawable/worldmap"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
And my activity file(i had just started it..)
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class LineMapActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView map_image = (ImageView)findViewById(R.id.main_imagemap);
}
}
And as in that link, i had also added MyImageView.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.widget.ImageView;
public class MyImageView extends ImageView
{
public MyImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawLine(0, 0, 20, 20, p);
super.onDraw(canvas);
}
}
Now how can i add this MyImageView to my app?
Finally I figured out a solution. It's a simple program which draws a line over an Image.
Here is my main.xml file (com.ImageDraw.MyImageView is my custom view, code below):
<?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" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.ImageDraw.MyImageView android:id="#+id/main_imagemap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
And here is the main activity:
import android.app.Activity;
import android.os.Bundle;
public class MyActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and this is my custom image view (MyImageView):
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MyImageView extends SurfaceView implements SurfaceHolder.Callback
{
private CanvasThread canvasthread;
public MyImageView(Context context) {
super(context);
getHolder().addCallback(this);
canvasthread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
public MyImageView(Context context, AttributeSet attrs)
{
super(context,attrs);
getHolder().addCallback(this);
canvasthread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
protected void onDraw(Canvas canvas) {
Log.d("ondraw", "ondraw");
Paint p = new Paint();
Bitmap mapImg = BitmapFactory.decodeResource(getResources(), R.drawable.mybitmap);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mapImg, 0, 0, null);
p.setColor(Color.RED);
canvas.drawLine(0, 0, 100, 100, p);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
canvasthread.setRunning(true);
canvasthread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
canvasthread.setRunning(false);
while (retry)
{
try
{
canvasthread.join();
retry = false;
}
catch (InterruptedException e) {
// TODO: handle exception
}
}
}
}
And finally here is my CanvasThread:
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class CanvasThread extends Thread
{
private SurfaceHolder surfaceHolder;
private MyImageView myImageView;
private boolean run = false;
public CanvasThread(SurfaceHolder s, MyImageView m)
{
surfaceHolder = s;
myImageView = m;
}
public void setRunning(boolean r)
{
run = r;
}
public void run()
{
Canvas c;
while(run)
{
c=null;
try
{
c= surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
myImageView.onDraw(c);
}
}
finally
{
if(c!=null)
{
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
You can find more details in this tutorial
Error you are getting because you are trying to casting ImageView object to MyImageView object.
Just fix the xml to include your object instead of an imageview like so (note that com.your.package.MyImageView should be the full package name of the package containing your class and then the class name)
<?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" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.your.package.MyImageView android:id="#+id/main_imagemap"
android:src="#drawable/worldmap"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>

Categories

Resources