How to clear canvas in a surface view? - android

I am developing an Android Digital signature app in which user can sign and i have to save this file as image.i am using SurfaceView for drawing. DigitalSignatureActivity has two Buttons Save,Clear.
1.Save Button to save file as image
2.Clear Button to clear surface.
But i am unable to clear the surface.i tried drawingSurface.setBackgroundColor(Color.BLACK); still previous sign is retained and canvas.drawColor(Color.BLACK); has no effect and
i am able to save file but its not storing signature perfectly(Some contents are missing) please help.
My code is:
DigitalSignatureActivity.java
package com.pop.digitalsign;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class DigitalSignatureActivity extends Activity implements
View.OnTouchListener {
private DrawingSurface drawingSurface;
private DrawingPath currentDrawingPath;
private Paint currentPaint;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setCurrentPaint();
drawingSurface = (DrawingSurface) findViewById(R.id.drawingSurface);
drawingSurface.setOnTouchListener(this);
}
private void setCurrentPaint() {
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(Color.WHITE);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(2);
}
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
drawingSurface.setBackgroundColor(0);
currentDrawingPath = new DrawingPath();
currentDrawingPath.paint = currentPaint;
currentDrawingPath.path = new Path();
currentDrawingPath.path.moveTo(motionEvent.getX(),
motionEvent.getY());
currentDrawingPath.path.lineTo(motionEvent.getX(),
motionEvent.getY());
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
currentDrawingPath.path.lineTo(motionEvent.getX(),motionEvent.getY());
drawingSurface.addDrawingPath(currentDrawingPath);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
currentDrawingPath.path.lineTo(motionEvent.getX(),motionEvent.getY());
}
return true;
}
//To save file as Image
public void saveDrawing(View v) throws IOException {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MySignatures");
Bitmap nBitmap = drawingSurface.getBitmap();
try {
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile = new File(mediaStorageDir.getPath()
+ File.separator + "SIGN_" + timeStamp + ".png");
FileOutputStream out = new FileOutputStream(mediaFile);
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Toast.makeText(this, "Signature saved to " + mediaFile,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Not saved",
Toast.LENGTH_SHORT).show();
}
}
//To clear Surface
public void clearScreen(View v) {
//drawingSurface.setBackgroundColor(Color.BLACK);
drawingSurface.clear();
}
}
DrawingSurface.java
package com.pop.digitalsign;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class DrawingSurface extends SurfaceView implements SurfaceHolder.Callback {
private Boolean _run;
protected DrawThread thread;
private Bitmap mBitmap;
Canvas canvas;
private CommandManager commandManager;
public DrawingSurface(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
commandManager = new CommandManager();
thread = new DrawThread(getHolder());
}
class DrawThread extends Thread{
public SurfaceHolder mSurfaceHolder;
public DrawThread(SurfaceHolder surfaceHolder){
mSurfaceHolder = surfaceHolder;
}
public DrawThread() {
// TODO Auto-generated constructor stub
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
canvas = null;
while (_run){
try{
canvas = mSurfaceHolder.lockCanvas(null);
//canvas.drawColor(Color.WHITE);
if(mBitmap == null){
mBitmap = Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);;
}
final Canvas c = new Canvas (mBitmap);
c.drawColor(0, PorterDuff.Mode.CLEAR);
commandManager.executeAll(c);
canvas.drawBitmap (mBitmap, 0, 0,null);
} finally {
if(canvas!=null){
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
public void addDrawingPath (DrawingPath drawingPath){
commandManager.addCommand(drawingPath);
}
public void clear(){
//Here i want to clear surface
canvas.drawColor(Color.BLACK);//it has no effect
}
public boolean hasMoreUndo(){
return commandManager.hasMoreUndo();
}
public Bitmap getBitmap(){
return mBitmap;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
mBitmap = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);;
}
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
CommandManager.java
package com.pop.digitalsign;
import android.graphics.Canvas;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
public class CommandManager {
private List<DrawingPath> currentStack;
public CommandManager(){
currentStack = Collections.synchronizedList(new ArrayList<DrawingPath>());
}
public void addCommand(DrawingPath command){
currentStack.add(command);
}
public void undo (){
final int length = currentStackLength();
if ( length > 0) {
final DrawingPath undoCommand = currentStack.get( length - 1 );
currentStack.remove( length - 1 );
undoCommand.undo();
}
}
public int currentStackLength(){
final int length = currentStack.toArray().length;
return length;
}
public void executeAll( Canvas canvas){
if( currentStack != null ){
synchronized( currentStack ) {
final Iterator<?> i = currentStack.iterator();
while ( i.hasNext() ){
final DrawingPath drawingPath = (DrawingPath) i.next();
drawingPath.draw( canvas );
}
}
}
}
public boolean hasMoreUndo(){
return currentStack.toArray().length > 0;
}
}
DrawingPath.java
package com.pop.digitalsign;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
public class DrawingPath {
public Path path;
public Paint paint;
public void draw(Canvas canvas) {
canvas.drawPath( path, paint );
}
public void undo() {
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#android:color/white" >
<com.pop.digitalsign.DrawingSurface
android:id="#+id/drawingSurface"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center" >
<Button
android:id="#+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="saveDrawing"
android:text="#string/save" />
<Button
android:id="#+id/clearBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clearScreen"
android:text="#string/clear" />
</LinearLayout>
</RelativeLayout>

the best suggestion i have is to use this
if (surfaceHolder.getSurface().isValid()) {
Canvas c = surfaceHolder.lockCanvas();
if (first >= 0) {
c.drawARGB(255, 255, 255, 255);
first--;
}
The value of first is 2 you can use what every name you want.
The reason is that the canvas is double buffered so you need to clear both screen by painting it white.
This stops the flickering

canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

In DrawingSurface add this method
public void resetCanvas(){ commandManager.clearAllPath(); }
and call this method, when you need to action for clear..
objectNameofDrawingSurefaceClass.resetCanvas();
add the code in CommandManager
public void clearAllPath(){currentStack.clear(); }
ok..

Related

Android: unresponsive thread when a new activity for result is started

I am new to Android so I am making a coloring book app just to get myself acquainted to android programming. I have looked up my problem extensively and implemented the solutions but still no progress.
I have an activity 'ColoringActivity' which calls a class 'PaintView' which extends surfaceview. I am trying to update the canvas in a separate thread. I also have a button in the layout which takes the user to another activity for picking colors. The problem is that when the user returns after choosing the color, the canvas becomes empty and I cant draw on the canvas anymore. I think i somehow loose the thread in between activities and although the thread is running in the background, I have no access to it.
I read on this forum that I must implement pause() and resume() methods in the thread class and basically kill the thread when I go to another activity and restart it when I return. Also I read I have to override onPause() and onResume() method in activity class and construct the surfaceview in onResume() so that it is constructed every time user returns to this activity.
I am sorry if it doesnt make much sense because I am lost as well.
My 'ColoringActivity':
package com.ali.coloryourself;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class ColoringActivity extends Activity {
private static final int COLOR_REQUEST_CODE = 100;
public static String file;
public static Bitmap bitmap;
BitmapFactory.Options options;
PaintView paintView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
Intent intent = getIntent();
file = intent.getStringExtra("fileName");
// paintView = (PaintView) findViewById(R.id.drawingSurface);
}
#Override
protected void onResume() {
paintView = (PaintView) findViewById(R.id.drawingSurface);
paintView.getThread().resume();
super.onResume();
}
#Override
protected void onPause() {
paintView.getThread().pause();
super.onPause();
}
public void pickColor(View v) {
paintView.getThread().pause();
Intent colorIntent = new Intent(this, ColorPickerActivity.class);
startActivityForResult(colorIntent, COLOR_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
if (requestCode == COLOR_REQUEST_CODE) {
int color = data.getIntExtra("Color", -1);
// paintView.getPaint().setColor(color);
}
}
}
}
My 'PaintView' class:
package com.ali.coloryourself;
import android.R.color;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class PaintView extends SurfaceView implements SurfaceHolder.Callback {
private Paint paint = new Paint();
private Canvas canvas;
private PaintThread thread;
private Path path = new Path();
private Bitmap bitmap;
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(3);
setThread(new PaintThread(holder));
}
class PaintThread extends Thread {
private boolean mRun;
private SurfaceHolder mSurfaceHolder;
private int mMode;
public static final int STATE_PAUSE = 2;
public static final int STATE_RUNNING = 4;
public PaintThread(SurfaceHolder surfaceHolder) {
mSurfaceHolder = surfaceHolder;
}
#Override
public void run() {
while (mRun) {
try {
canvas = mSurfaceHolder.lockCanvas(null);
if (mMode == STATE_RUNNING) {
if (bitmap == null) {
bitmap = Bitmap.createBitmap(1, 1,
Bitmap.Config.ARGB_8888);
}
}
doDraw(canvas);
canvas.drawBitmap(bitmap, 0, 0, null);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null) {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
private void doDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
public void setRunning(boolean b) {
mRun = b;
}
public void pause() {
if (mMode == STATE_RUNNING)
setState(STATE_PAUSE);
}
public void resume() {
setState(STATE_RUNNING);
}
public void setState(int mode) {
synchronized (mSurfaceHolder) {
mMode = mode;
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Log.d("Touch", "I am touching");
float eventX = event.getX();
float eventY = event.getY();
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
return true;
}
public void surfaceCreated(SurfaceHolder holder) {
if (getThread().getState() == Thread.State.NEW) {
getThread().setRunning(true);
getThread().start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
getThread().setRunning(false);
getThread().resume();
while (retry) {
try {
getThread().join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public Paint getPaint() {
return paint;
}
public void setPaint(int color) {
this.paint.setColor(color);
}
public PaintThread getThread() {
return thread;
}
public void setThread(PaintThread thread) {
this.thread = thread;
}
}
my 'activity_draw.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:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="pickColor"
android:text="Pick Color" />
<com.ali.coloryourself.PaintView
android:id="#+id/drawingSurface"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:layout_marginTop="10dp"/>
</RelativeLayout>
I know I am missing some very basic thread concept. I need to allow the user to pick color and return and be able to continue drawing. I will be extremely grateful for your help.
I think I have found an answer although I am not sure if it is a good programming practice. I found out that my surface view and thread were created once 'ColoringActivity' was created and destroyed every time 'ColoringActivity' went to background. But once 'ColoringActivity' was restarted and resumed, surface view and thread were not recreated. So i moved the following line
setContentView(R.layout.activity_draw);
to onResume() method and now I can draw on the canvas every time. Now I just need to save the canvas and re load it when the activity comes back on to start off the coloring where the user left it.

cant create Region while drawing on android canvas

I have this code
package com.cerbertek;
import java.util.ArrayList;
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.graphics.Region;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class PlayGameView extends SurfaceView implements SurfaceHolder.Callback {
private CanvasThread canvasthread;
private Context mContext;
private Region firstRec;
private ArrayList<Region> regions;
private class CanvasThread extends Thread {
private SurfaceHolder _holder;
private boolean _run = false;
public CanvasThread(SurfaceHolder surfaceHolder) {
_holder = surfaceHolder;
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _holder.lockCanvas(null);
synchronized (_holder) {
onDraw(c);
}
} finally {
if (c != null) {
_holder.unlockCanvasAndPost(c);
}
}
}
}
}
public PlayGameView (Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
canvasthread = new CanvasThread(getHolder());
setFocusable(true);
}
#Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint ();
Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
canvas.drawColor(Color .BLACK);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
int left = canvas.getWidth()/2 - wrench.getWidth()*2 + j*wrench.getWidth();
int top = 0 + i*wrench.getHeight();
canvas.drawBitmap(wrench, left, top, null);
Log.d(i + " " + j, left+ " " + top);
Region reg = new Region(left, top, left + wrench.getWidth(), top + wrench.getHeight());
regions.add(reg);
}
}
}
public ArrayList<Region> getRegions() {
return regions;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
canvasthread.setRunning(true);
canvasthread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
boolean retry = true;
canvasthread.setRunning(false);
while (retry) {
try {
canvasthread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
in onDraw() method I want to create a Region and add it to ArrayList, that returning by getRegions() method.
But it now works!
I saw first image and then NullPoiterExeption on regions.add(reg); line.
Please hlp me
In the constructor put:
regions = new ArrayList<Region>();
You were forgetting to initialize it.

android canvas click

there is class, that draws on canvas some field
package com.cerbertek;
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.graphics.Region;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class PlayGameView extends SurfaceView implements SurfaceHolder.Callback {
private CanvasThread canvasthread;
private Context mContext;
private Region firstRec;
private class CanvasThread extends Thread {
private SurfaceHolder _holder;
private boolean _run = false;
public CanvasThread(SurfaceHolder surfaceHolder) {
_holder = surfaceHolder;
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _holder.lockCanvas(null);
synchronized (_holder) {
onDraw(c);
}
} finally {
if (c != null) {
_holder.unlockCanvasAndPost(c);
}
}
}
}
}
public PlayGameView (Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
canvasthread = new CanvasThread(getHolder());
setFocusable(true);
}
#Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint ();
Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
canvas.drawColor(Color .BLACK);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
int left = canvas.getWidth()/2 - wrench.getWidth()*2 + j*wrench.getWidth();
int top = 0 + i*wrench.getHeight();
canvas.drawBitmap(wrench, left, top, null);
Log.d(i + " " + j, left+ " " + top);
}
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
canvasthread.setRunning(true);
canvasthread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
boolean retry = true;
canvasthread.setRunning(false);
while (retry) {
try {
canvasthread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
so i want to detect where i click on(for exemple there is 2 rects and i want to detect what rect i click on). i can set setOnClickListener to my view, but how to get position of click?
then i want to set the regions while drawing( it is right, yeah? or not?) and in activity i'll check is click coordinates contains regions
so
1) how can i get coord of click
2) what is the pretty good way to do do all that stuff, because my ideas are poor often
Look at the setOnTouchListener.
The OnTouchListener implements a method with the following signature:
public boolean onTouch(View v, MotionEvent event)
The MotionEvent has information about where the touch actually happened. (event.getX() and event.getY())

How to make SurfaceView with transparent background?

I have simple layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/backgroundtimer"
android:orientation="vertical" >
<TextView
android:id="#+id/TextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/hello" />
<com.fmech.zenclock.surface.ZenClockSurface
android:id="#+id/zenClockSurface1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
And a have ZenClockSurface class
package com.fmech.zenclock.surface;
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.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ZenClockSurface extends SurfaceView implements SurfaceHolder.Callback{
private DrawClock drawClock;
public ZenClockSurface(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
getHolder().addCallback(this);
}
public ZenClockSurface(Context context) {
super(context);
this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
getHolder().addCallback(this);
}
public ZenClockSurface(Context context, AttributeSet attrs) {
super(context, attrs);
this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
getHolder().addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//this.getHolder().setFormat(PixelFormat.TRANSPARENT);
drawClock = new DrawClock(getHolder(), getResources());
drawClock.setRunning(true);
drawClock.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
// завершаем работу потока
drawClock.setRunning(false);
while (retry) {
try {
drawClock.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
class DrawClock extends Thread{
private boolean runFlag = false;
private SurfaceHolder surfaceHolder;
private Bitmap picture;
private Matrix matrix;
private long prevTime;
private Paint painter;
public DrawClock(SurfaceHolder surfaceHolder, Resources resources){
this.surfaceHolder = surfaceHolder;
this.surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
picture = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher);
matrix = new Matrix();
this.painter=new Paint();
this.painter.setStyle(Paint.Style.FILL);
}
public void setRunning(boolean run) {
runFlag = run;
}
#Override
public void run() {
Canvas canvas;
while (runFlag) {
matrix.preRotate(1.0f, picture.getWidth() / 2, picture.getHeight() / 2);
canvas = null;
try {
//surfaceHolder.getSurface().setAlpha(0.5f);
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(picture, matrix, this.painter);
}
}
finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
And code of activity
package com.fmech.zenclock.surface;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.os.Bundle;
public class ZenClockSurfaceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
}
}
I want what background color of android picture was tranparent but i get black background.
I have background on RelativeLayout with some picture bu SurfaceView rotate Android icon with no transparent.
How i can do transparent?
Yeah, i did it i solve problem
Activity code
package com.fmech.zenclock.surface;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ZenClockSurfaceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ZenClockSurface sfvTrack = (ZenClockSurface)findViewById(R.id.zenClockSurface1);
sfvTrack.setZOrderOnTop(true); // necessary
SurfaceHolder sfhTrack = sfvTrack.getHolder();
sfhTrack.setFormat(PixelFormat.TRANSLUCENT);
}
}
Surface Code
package com.fmech.zenclock.surface;
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.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.Surface.OutOfResourcesException;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ZenClockSurface extends SurfaceView implements
SurfaceHolder.Callback {
private DrawClock drawClock;
public ZenClockSurface(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getHolder().addCallback(this);
}
public ZenClockSurface(Context context) {
super(context);
getHolder().addCallback(this);
}
public ZenClockSurface(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
drawClock = new DrawClock(getHolder(), getResources());
drawClock.setRunning(true);
drawClock.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
drawClock.setRunning(false);
while (retry) {
try {
drawClock.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
class DrawClock extends Thread {
private boolean runFlag = false;
private SurfaceHolder surfaceHolder;
private Bitmap picture;
private Matrix matrix;
private Paint painter;
public DrawClock(SurfaceHolder surfaceHolder, Resources resources) {
this.surfaceHolder = surfaceHolder;
picture = BitmapFactory.decodeResource(resources,
R.drawable.ic_launcher);
matrix = new Matrix();
this.painter = new Paint();
this.painter.setStyle(Paint.Style.FILL);
this.painter.setAntiAlias(true);
this.painter.setFilterBitmap(true);
}
public void setRunning(boolean run) {
runFlag = run;
}
#Override
public void run() {
Canvas canvas;
while (runFlag) {
matrix.preRotate(1.0f, picture.getWidth() / 2,
picture.getHeight() / 2);
canvas = null;
try {
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
canvas.drawBitmap(picture, matrix, this.painter);
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
It's work.
In API 3 and 4, you cannot put anything behind a SurfaceView. Quoting Dianne Hackborn:
The surface view is actually BEHIND your window, and a hole punched in the window for you to see it. You thus can put things on top of it in your window, but nothing in your window can appear behind it.
http://groups.google.com/group/android-developers/browse_thread/thread/8d88ef9bb22da574
From API 5 onwards you can use setZOrderOnTop. The trick is that you have to do it in your constructor so it gets called before the view is attached to the window:
public ZenClockSurface(Context context, AttributeSet attrs) {
super(context, attrs);
setZOrderOnTop(true);
SurfaceHolder holder = getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
}

Application error when drawing to SurfaceView

I'm am doing a simple coding attempt trying to draw on a SurfaceView created on my main.xml layout. I can change background color and display an icon fine, but when I try to draw I get an error. I am a newbie so obvious I am missing something, please lend a helping hint, thanks!
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<SurfaceView android:id="#+id/Paper"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</SurfaceView>
</LinearLayout>
and code here;
package com.example.SurfaceViewTest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceViewTest extends Activity implements SurfaceHolder.Callback {
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Paint paint;
Bitmap mDrawing;
boolean mRun;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView = (SurfaceView) this.findViewById(R.id.Paper);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceView.setBackgroundColor(Color.rgb(0, 255, 0));
mRun=true;
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
Thread thread = new Thread(){
public void doDraw(Canvas c){
mDrawing = Bitmap.createBitmap(200, 300, Bitmap.Config.RGB_565);
c.setBitmap(mDrawing);
paint = new Paint();
paint.setColor(Color.rgb(255, 255,255));
c.drawLine(1,1,200,300, paint);
}
public void run() {
while (mRun) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
doDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
};
}
UPDATE:
Ok I got it to works thanks!
package com.example.SurfaceViewTest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceViewTest extends Activity implements SurfaceHolder.Callback {
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
Bitmap mDrawing;
Canvas tempCanvas = new Canvas();
Paint paint;
boolean mRun;
int intCanvasWidth, intCanvasHeight;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView = (SurfaceView) this.findViewById(R.id.Paper);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
intCanvasWidth = width;
intCanvasHeight = height;
mDrawing = Bitmap.createBitmap(intCanvasWidth, intCanvasHeight,
Bitmap.Config.RGB_565);
paint = new Paint();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (thread.getState() == Thread.State.TERMINATED) {
thread = new Thread();
}
mRun = true;
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mRun = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
Thread thread = new Thread() {
public void doDraw(Canvas c) {
tempCanvas.setBitmap(mDrawing);
paint.setColor(Color.rgb(255, 255,255));
tempCanvas.drawLine(1,1,200,300, paint);
c.drawBitmap(mDrawing, 0, 0, null);
}
#Override
public void run() {
Canvas c;
while (mRun) {
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
doDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
};
}
Here's how my SurfaceView works. I think your problem is doing your Bitmap in surfaceCreated().
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.start();
}
Thread thread = new Thread(){
...
public void doDraw(Canvas c){
//draw onto the canvas here
}
public void run() {
while (mRun) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
doDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
};

Categories

Resources