Android SurfaceView draws bitmap multiple times - android

I'm trying to draw a bitmap into surfaceView I can successfully draw but I need to move that bitmap around the screen based on some other user movements but when I set
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(bitmap, left, top, null);
It draws same bitmap multiple times in screen.
But when I do this way
canvas.drawColor(Color.GREEN);
canvas.drawBitmap(bitmap, left, top, null);
It works correctly draws just one bitmap and moves it , but I need transparent background not colored.
CODE
public class DotsSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private boolean created;
Bitmap bitmap;
#Override
public void surfaceCreated(SurfaceHolder holder) {
// draw();
created = true;
}
#Override
// This is always called at least once, after surfaceCreated
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// draw();
created = true;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public DotsSurfaceView(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
holder.setFormat(PixelFormat.TRANSPARENT);
Drawable drawable = ARTrackingActivity.contexti.getDrawable(R.drawable.ic_tune_black_24px);
bitmap =Utils.drawableToBitmap(drawable);
}
public void draw(float left, float top) {
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
synchronized (holder) {
draw2(canvas, left, top);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
public void draw2(Canvas canvas, float left, float top) {
if (created) {
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(bitmap, left, top, null);
}
}
}

Related

How to make Circular Mask and Clip GLSurfaceView?

I work with an SDK that provides a rectangular GLSurfaceView through a callback.
I want to be able to render this view in a circular layout. (i.e.) I would like to display the view on a circular view
It's showing Circle shape when I overlay GLSurfaceView over ImageView
GLSurfaceView over ImageView
It's showing Square shape when I overlay GLSurfaceView over VideoView.
GLSurfaceView over VideoView
I have tried below code for making circle GLSurfaceView
public class SampleGLView extends GLSurfaceView implements View.OnTouchListener {
private Path clippingPath;
public SampleGLView(Context context) {
this(context, null);
}
public SampleGLView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnTouchListener(this);
}
private TouchListener touchListener;
#Override
public boolean onTouch(View v, MotionEvent event) {
final int actionMasked = event.getActionMasked();
if (actionMasked != MotionEvent.ACTION_DOWN) {
return false;
}
if (touchListener != null) {
touchListener.onTouch(event, v.getWidth(), v.getHeight());
}
return false;
}
public interface TouchListener {
void onTouch(MotionEvent event, int width, int height);
}
public void setTouchListener(TouchListener touchListener) {
this.touchListener = touchListener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw || h != oldh) {
int radius = Math.min(w, h)/2;
clippingPath = new Path();
clippingPath.addCircle(w/2, h/2, radius, Path.Direction.CW);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
int count = canvas.save();
canvas.clipPath(clippingPath);
super.dispatchDraw(canvas);
canvas.restoreToCount(count);
}
}
Question:
How do I go about clipping and rendering this as a circle?
(The background is constantly changing, so i cant overlay a transparent view on top of this video view. The aim is to have a rectangular glsurface view on top of which there is a circular glsurface view)
Is any one have idea how to solve please comment. Thanks in advance.

How to make Circular Mask and Clip GLSurfaceView in android?

I work with an SDK that provides a rectangular GLSurfaceView through a callback.
I want to be able to render this view in a circular layout. (i.e.) I would like to display the view on a circular view
It's showing Circle shape when I overlay GLSurfaceView over ImageView
GLSurfaceView over ImageView
It's showing Square shape when I overlay GLSurfaceView over VideoView.
GLSurfaceView over VideoView
I have tried below code for making circle GLSurfaceView
public class SampleGLView extends GLSurfaceView implements View.OnTouchListener {
private Path clippingPath;
public SampleGLView(Context context) {
this(context, null);
}
public SampleGLView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnTouchListener(this);
}
private TouchListener touchListener;
#Override
public boolean onTouch(View v, MotionEvent event) {
final int actionMasked = event.getActionMasked();
if (actionMasked != MotionEvent.ACTION_DOWN) {
return false;
}
if (touchListener != null) {
touchListener.onTouch(event, v.getWidth(), v.getHeight());
}
return false;
}
public interface TouchListener {
void onTouch(MotionEvent event, int width, int height);
}
public void setTouchListener(TouchListener touchListener) {
this.touchListener = touchListener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw || h != oldh) {
int radius = Math.min(w, h)/2;
clippingPath = new Path();
clippingPath.addCircle(w/2, h/2, radius, Path.Direction.CW);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
int count = canvas.save();
canvas.clipPath(clippingPath);
super.dispatchDraw(canvas);
canvas.restoreToCount(count);
}
}
Question:
How do I go about clipping and rendering this as a circle?
(The background is constantly changing, so i cant overlay a transparent view on top of this video view. The aim is to have a rectangular glsurface view on top of which there is a circular glsurface view)
Is any one have idea how to solve please comment. Thanks in advance.

Move image left to right using surfaceview android

I am trying to understand using surfaceview. I want an image to move from left to right using surfaceview. Currently image is drawn but I am unable to make it move. Where should I call the variables x1 and y1. Also how could I call the invalidate() method, I want to make the image move from left to right repeatedly. Thanks
public class GameBoardTwo extends SurfaceView {
private Bitmap bitmap1;
private SurfaceHolder holder;
int x1, y1;
public GameBoardTwo(Context context) {
super(context);
holder = getHolder();
bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
init();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = holder.lockCanvas(null);
drawSomething(c);
holder.unlockCanvasAndPost(c);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
}
private void init(){
x1 = 0;
y1 = 100;
}
protected void drawSomething(Canvas canvas) {
canvas.drawColor(Color.WHITE);
if(x1 < canvas.getWidth()){
x1 += 5;
}
else{
x1 = 0;
}
canvas.drawBitmap(bitmap1, x1, y1, null);
}
}
You need to use thread/runnable inteface and override run(). Something like this:
#Override
protected void run(){
while(true){
drawSomething(c);//c is your locked canvas
try{
Thread.sleep(50)
} catch(Exception e){}
}
}

canvas zoom in partially

I want to zoom in the canvas board partially as the letter tray button will be fixed and the board will be zoom,
The partially coding is as mention below and the screen is fully draw in canvas which can be viewed as mention at the bottom.. please help and thanks for you concern.
public class BoardView extends SurfaceView implements SurfaceHolder.Callback
{
class DrawingThread extends Thread implements OnTouchListener {
public DrawingThread(SurfaceHolder holder, Handler handler) {
mSurfaceHolder = holder;
public void setRunning(boolean b) {
mRun = b;
}
#Override
public void run() {
while (mRun) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
// System.gc();
// c.scale(canvasScaleX, canvasScaleY);
// c.save();
// c.translate(canvasTranslateX, canvasTranslateY);
doDraw(c);
}
updateGame();
} finally {
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
private void doDraw(Canvas canvas) {
if (ge == null)
return;
Rect bRect = new Rect(0, 0, dims.getTotalWidth(),
dims.getScoreHeight() + dims.getBoardheight());
Drawable drawable = getResources().getDrawable(R.drawable.board);
drawable.setBounds(bRect);
drawable.draw(canvas);
Rect tRect = new Rect(0, dims.getScoreHeight()
+ dims.getBoardheight(), dims.getTotalWidth(),
dims.getTotalHeight());
canvas.drawRect(tRect, fillTrayPaint);
int topHeight = dims.getScoreHeight() + dims.getBoardheight();
int bottom = (dims.getTotalHeight() + 5)
- (dims.getTotalWidth() / Tray.TRAY_SIZE);
Rect rect = new Rect(0, topHeight, dims.getTotalWidth(), bottom - 7);
Drawable drawableTray = getResources()
.getDrawable(R.drawable.strip);
drawableTray.setBounds(rect);
drawableTray.draw(canvas);
drawTray(canvas);
drawBoard(canvas);
// drawScore(canvas);
drawMovingTile(canvas);
}
public BoardView(Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// endTurn=(ImageButton)findViewById(R.id.endturn_button_horizontal);
thread = new DrawingThread(holder, handler);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
final float scale1 = getResources().getDisplayMetrics().density;
defaultFontSize = (int) (MIN_FONT_DIPS * scale1 + 0.5f);
thread.setDefaultFontSize(defaultFontSize);
dimensions = calculateDimensions(getWidth(), getHeight());
thread.setDimensions(dimensions);
thread.setRunning(true);
// if (thread != null && !thread.isAlive())
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
We can simply do it by canvas.clipRect(rectangle), at this point what we are suppose to do is save the canvas canvas.save() and after canvas.clipRect(rectangle) call canvas.restore().
Consider trying something like this:
Create a bitmap from the canvas you wish to zoom into.
When rendering that bitmap to the screen, you can change the scr rect
(which will "zoom" into the bitmap).
I hope this helps.
I think you need to render your game board into offscreen bitmap and then draw this bitmap at canvas using Matrix, so you will be able to change its position and scale.
I believe the easiest way to do this would be to use Canvas#scale(float scale, int pivotx, int pivoty) method. It essentially grows the entire canvas uniformally which really is what zooming is from a 2D perspective.
canvas.scale(2.0f, getWidth()/2, getHeight()/2) will scale the image by 2 from the center. canvas.scale(1.0f, getWidth()/2, getHeight()/2) will shrink it back.
I have never tried this in this context, so if you decide to try it report back the results please! I'd like to know for future reference.

How I can move an image from left to right and right to left in android?

I'm new in android. I want to move an image from left to right and right to left.When user touch right side image of the image it will move right side.Same thing will happen when user will touch right side of the image.But image will move predefine point across x-axis.
For example: Image will move p1(100,100), p2(150,100), p3(200,100), p4(250,100) across those points sequentially. If user touch left side of p1, it will remain current position.Same thing will occurs at p4. I can move image from p1 to p2 and p2 to p1. when I add p3 and p4 it's not working as I expected.
Here is my GameView class.
public class GameView extends SurfaceView{
private Bitmap BG_image;
private SurfaceHolder holder;
//private GameLoopThread gameLoopThread;
int x;
int y;
private int srcX=100;
private int srcY=100;
int replaceX=0,areaThreshold=50;
int distance=50;
public GameView(Context context) {
super(context);
//gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
/* boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}*/
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
/* gameLoopThread.setRunning(true);
gameLoopThread.start();*/
Canvas c = holder.lockCanvas(null);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
BG_image = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Bitmap.createScaledBitmap(BG_image, BG_image.getWidth(), BG_image.getHeight(), false);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
// x = (int) ev.getX();
// y = (int) ev.getY();
updateX(srcX);
replaceX=(int)ev.getX();
int StartX=0, EndX=0;
StartX=replaceX-areaThreshold;
EndX=replaceX+areaThreshold;
if(StartX<=100){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=100;
}
else if(StartX>100 && StartX<250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=srcX+distance;
}
if(EndX>100 && EndX<250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=srcX-distance;
}
else if(EndX>250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=250;
}
return super.onTouchEvent(ev);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
updateX(srcX);
Paint paint = new Paint();
canvas.drawColor(Color.BLACK);
canvas.drawRect(new Rect(0,0,getWidth(),getHeight()),paint);
canvas.drawBitmap(BG_image, srcX, srcY, null);
}
private int updateX(int srcX){
this.srcX =srcX;
return srcX ;
}
}
Please review my code and give your valuable advice to solve my problem.
Hopefully, I will get a reply soon!
This is very easy with Android TranslateAnimation
ImageView img_animation = (ImageView) findViewById(R.id.img_animation);
TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(5000); // animation duration
animation.setRepeatCount(5); // animation repeat count
animation.setRepeatMode(2); // repeat animation (left to right, right to left )
//animation.setFillAfter(true);
img_animation.startAnimation(animation); // start animation
find more details from here move an image from left to right and right to left in android
Now, I understand my problem. Thank you very much to give your suggestion.
Here is my updated code.
public class GameView extends SurfaceView{
private Bitmap BG_image;
private SurfaceHolder holder;
int x=100;
private int srcX=100;
private int srcY=100;
int distance=50;
public GameView(Context context) {
super(context);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = holder.lockCanvas(null);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
BG_image = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Bitmap.createScaledBitmap(BG_image, BG_image.getWidth(), BG_image.getHeight(), false);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
x = (int) ev.getX();
if(x-srcX>0)
srcX += distance;
else if(x-srcX<0)
srcX -= distance;
if(srcX<=100)
srcX = 100;
else if(srcX>250)
srcX = 250;
Log.w("ev.getX : srcX",x+" : "+srcX);
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
return super.onTouchEvent(ev);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint paint = new Paint();
canvas.drawColor(Color.BLACK);
canvas.drawRect(new Rect(0,0,getWidth(),getHeight()),paint);
canvas.drawBitmap(BG_image, srcX-BG_image.getWidth()/2, srcY, null);
}
}

Categories

Resources