Zoom effect on Android SurfaceView - android

I am developing a Car Race Game. I am able to move, stop, accelerate. But i want that when i press screen then car(bitmap of car image) should look like, it had jumped on its place.I am using surfaceviewto draw view
I do not want to use 3D openGL. Any help is much appreciated

finally i used.On touch event, i create a bigger bitmap and draw it on same place. So it will give zoom effect
Bitmap bitmapToZoom; // Create a Bitmap
// Now zoom it
bitmapToZoom=Bitmap.createScaledBitmap(bitmapToZoom, bitmapToZoom.getWidth()+30,bitmapToZoom.getHeight()+30, null);
//now draw it again
canvas.drawBitmap(bitmapToZoom, 0,0,null);
So now finally, Zooming actor on touch code will be like this. Class Name ZoomonTouc.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.SurfaceView;
public class ZoomonTouc extends SurfaceView {
public Bitmap mMyChracter;
public ZoomonTouc(Context context) {
super(context);
mMyChracter = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
setWillNotDraw(false);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mMyChracter, mMyChracter.getWidth()/2, mMyChracter.getHeight()/2, null);
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
RectF rectF = new RectF(mMyChracter.getWidth()/2, mMyChracter.getHeight()/2, mMyChracter.getWidth() + 100,
mMyChracter.getHeight() + 100);
if (rectF.contains(event.getX(), event.getY())) {
mMyChracter = Bitmap.createScaledBitmap(mMyChracter,
mMyChracter.getWidth() + 10, mMyChracter.getHeight() + 10,
false);
}
return true;
}
}
To test it properly create one activity and set above surface to activity background
setContentView(new ZoomonTouc(this));

Related

Drawing custom indoor map and links between locations. For each location x,y coordinates are already know to be shown on screen

package com.smallfan.museumexhibition.views;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.Toast;
public class CustomDrawableView extends View implements View.OnClickListener {
Drawable drawable;
Paint paint;
String myText;
int x1,y1;
Context context;
public CustomDrawableView(Context context, Drawable mydrawable, int x, int y, String text) {
super(context);
this.myText=text;
this.x1=x;
this.y1=y;
this.paint = new Paint();
this.context=context;
drawable=mydrawable;
drawable.setBounds(x, y, x + drawable.getMinimumWidth(), y + drawable.getMinimumHeight());
setOnClickListener(this);
}
protected void onDraw(Canvas canvas) {
drawable.draw(canvas);
}
#Override
public void onClick(View v)
{
v.setTag(myText);
Toast.makeText(context, "View clicked. "+" tag "+ v.getTag(), Toast.LENGTH_SHORT).show();
}
}
///////////////////////////////////////////////////
package com.smallfan.museumexhibition;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MapInActivity extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.v("MapInActivity", "onCreate()");
}
DrawView drawView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.v("MapInActivity", "onCreateView()");
View v = LayoutInflater.from(getActivity()).inflate(R.layout.indoormap_layout, null);
RelativeLayout maplayout=(RelativeLayout)v.findViewById(R.id.maplayout);
CustomDrawableView mCustomDrawableView = new CustomDrawableView(getActivity(),getResources().getDrawable(R.drawable.ic_launcher),10,10,"Item 1");
maplayout.addView(mCustomDrawableView);
CustomDrawableView mCustomDrawableView1 = new CustomDrawableView(getActivity(),getResources().getDrawable(R.drawable.ic_launcher),50,50,"Item 2");
maplayout.addView(mCustomDrawableView1);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
Log.v("MapInActivity", "onActivityCreated().");
}
//
}
I have to draw a map like this and also show the overlay on tap of any pin like in Google map. I was able to draw views on canvas along with click listeners, but the click listener action is performed by clicking any where on screen and it's just for the view drawn in last. So if any solution then please let me know. Thanks in advance.
Have you heard of GeoFencing ? The only catch is that it works on the principle of a circle. But that should not be that bad, since you can cover the entrance with 2 circles, 1 that covers the breath of the room and includes the entrance door, and the other circle contained within the bigger circle that only covers the door.
Check out A4, I have drawn 2 circles, sorry for a ugly representation.
If a user enters the smaller circle and the bigger circle than he is still in the room. If he enters the smaller circle and exists it (and is not entering the bigger circle) he has exited the room.
Twisted but will work with minimal coding. Just read up geofencing.
Also note geofencing is now merged with LocationClient API's which consume 8 times lesser battery as compared to LocationManager. So go for it.

How to draw a dot that leaves a trail

I'm still learning Android, and I decided to download an example paint application to fiddle with that and learn a bit about how Android handles graphics/drawables/painting. The code I have shows a green and red 'V' in the upper left corner, and a red dot that follows where you touch.
However, I found that the screen is being redrawn each time, so I can't use it as a painting tool. It's almost as if I'm dumping a bucket of white paint over the surface and then redrawing the circle. How can I make it so that the red dot that follows your finger leaves a trail? Here's the code.
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity implements OnTouchListener {
private float x;
private float y;
private int moveX;
Paint paint = new Paint();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyCustomPanel view = new MyCustomPanel(this);
ViewGroup.LayoutParams params =
new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
addContentView(view, params);
view.setOnTouchListener(this);
}
private class MyCustomPanel extends View {
public MyCustomPanel(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.GREEN);
paint.setStrokeWidth(6);
canvas.drawLine(moveX,10,50,50,paint);
paint.setColor(Color.RED);
canvas.drawLine(50, 50, 90, 10, paint);
canvas.drawCircle(50, 50, 3, paint);
moveX++;
canvas.drawCircle(x,y,3,paint);
}
}
public boolean onTouch(View v, MotionEvent event) {
x = event.getX();
y = event.getY();
v.invalidate();
return true;
}
}
For example, save the circles in an ArrayList. Make an ArrayList and save every xy coordinates from touch as a point.The following code is just from scratch, could not test it at the moment, so if anything is not working let me know and I will give a an example when I am at home.
private ArrayList<Point> pointList = new ArrayList<Point>
Then in On Touch:
Point xyPoint = new Point();
xyPoint.x = event.getX();
xyPoint.y = event.getY();
pointList.add(xyPoint);
invalidate();
and in onDraw, do a for-loop to get all points and draw each one:
for(int i=0;i<pointList.size();i++){
Point p = pointList.get(i);
canvas.drawCircle(p.x, p.y, 2, paint);
}
This draws circles with 2px diameter where Your finger touches. But this is just an simple example, there is a lot of more You can do and that look better. You should learn about draw on path and how to draw rects and ovales etc. Here is a good example of how to draw on path:
http://android-er.blogspot.de/2011/08/drawpath-on-canvas.html

in android canvas why the matrix is too slow and sluggish

I wanted to rotate image in android app around the center pivot and following is the code..
package com.android.maddy.canvs;
import android.content.Context;
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.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.view.MotionEvent;
import android.view.View;
public class drawview extends View {
private Drawable d[]=new Drawable[2];
Boolean done=false;
Handler h;
float th=0;
public drawview(Context context) {
super(context);
d[0]=context.getResources().getDrawable(R.drawable.appdatabk);
d[1]=context.getResources().getDrawable(R.drawable.appdata);
h = new Handler();
}
Runnable r =new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
th++;
invalidate();
}
};
public void onDraw(Canvas c){
super.onDraw(c);
Paint p =new Paint();
Rect imageBounds = c.getClipBounds(); // for the background
d[0].setBounds(imageBounds);
d[0].draw(c);
Matrix m = new Matrix();
m.setTranslate(getWidth()/2, getHeight()/2);
m.preRotate(th,43,160); //my image is 86x320
Bitmap b = BitmapFactory.decodeResource(getResources(),R.drawable.appdata);//image of the bottle i want to rotate
c.drawBitmap(b,m, p);
p.setColor(Color.BLUE);
h.postDelayed(r,1);
}
}
What happens here is that the matrix calculation slows down the speed of rotation and thus it gives ugly sluggish output..
If you have another method to rotate the image around center pivot without using matrix or there is some other method then
Please help me out..
I also removed the matrix and checked the rotation in drawBitmap() function using x+r*(Math.cos(th)) and y+r*(Math.sin(th)) that works fine but image doesn't rotate around pivot..
Please help..
Thanks
Matrix is quite fast. What is slowing you down is that you create classes and load bitmaps in the onDraw. Create the Paint and the Matrix one in the class, and also load the bitmap once
I had the same problem. I think what happens is the canvas stores the matrix values into an array and it fills up the more you rotate the canvas.
That same thing happens when you use Matrix.postRotate(degrees, px, py) and Canvas.concat(Matrix)

A simple one touch touch Drawing View but keep getting ACTION_CANCEL before touches completed

This has been driving me crazy.
I think I have everything in place but no matter what I do the touches seem to be cancelled before I lift my finger off the view. Even stranger I can draw long horizontal lines but vertical ones are always very short.
I am using a Samsung G SII 2.3.3 but building to 2.1
Ant ideas?
My sample code:
package com.mycompany.myviews;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View
{
private ArrayList<DrawPoint> points = new ArrayList<DrawPoint>();
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void addPoint(DrawPoint p)
{
points.add(p);
}
public boolean onTouchEvent (MotionEvent event)
{
DrawPoint p = new DrawPoint((int)event.getX(), (int)event.getY());
switch(event.getAction())
{
case android.view.MotionEvent.ACTION_DOWN:
p.start = true;
break;
case android.view.MotionEvent.ACTION_CANCEL:
Log.d("TouchView", "On Touch cancelled.");
break;
}
addPoint(p);
invalidate();
return true;
}
public void onDraw(Canvas c)
{
super.onDraw(c);
Path path = new Path();
for (int i = 0; i < points.size(); i++)
{
DrawPoint currentPoint = points.get(i);
if (currentPoint.start == true)
path.moveTo(currentPoint.p.x, currentPoint.p.y);
else
path.lineTo(currentPoint.p.x, currentPoint.p.y);
}
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.BLACK);
c.drawPath(path, paint);
}
private class DrawPoint
{
public boolean start = false;
public Point p;
DrawPoint(int x, int y)
{
p = new Point(x, y);
}
}
}
UPDATE: OK, I figured this out. Because this view is inside another View some of the touches are being intercepted by the parent or parents.
The solution I have found to be good enough for my needs is to add the following line into the case for ACTION_DOWN :
getParent().requestDisallowInterceptTouchEvent(true);
This then allows my view to get all touches.
I edited my answer...
I found a finger-painting example in the Android Samples, and also a discussion about that example on stackoverflow. Hope this helps you out.
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/FingerPaint.html
Android FingerPaint Example using Canvas, what is the offscreen Canvas?
My original post...
I don't have a solution, but did find a site that might give you some
ideas on what you could do...
http://bestsiteinthemultiverse.com/2008/11/android-graphics-example/
The solution I have found to be good enough for my needs is to add the following line into the case for ACTION_DOWN :
getParent().requestDisallowInterceptTouchEvent(true);
This then allows my view to get all touches.

Android LAYOUT xml / java error

I am trying to get a panel which has a canvas containing an image which i will place over another image and when i touch the screen the top(overlaying) image will be erased by means of a PoerterDuffXfermode(PorterDuff.Mode) etc ,, anyway I have the functionality done and dusted thanks to the help of a guy on this forum who provided some code which basically carried out exactly what I needed, but I'm having one slight problem,, the guys implementation of the code, will not allow me to reference the Panel class properly in XML to place the Panel on a pre defined XML (main.xml) file. its giving me an error stating
Custom view Panel is not using the 2- or 3-argument View constructors; XML attributes will not work
This is what my xml looks like on a basic scale (just the view in place within the outer linearlayout).
<com.easyscratch.full.Panel
xmlns:android="http://schemas.android.com/apk/res/android"
android:id ="#+id/easyCustView"
android:layout_width="300dp"
android:layout_height="300dp"
android:visibility="visible"
android:focusableInTouchMode="true"/>
The java is as followed .( PANEL CLASS)
package com.easyscratch.full;
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.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
class Panel extends View
{
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
Bitmap bitmap;
Canvas pcanvas ;
int x = 0;
int y =0;
int r =0;
public Panel(Context context) {
super(context);
Log.v("Panel", ">>>>>>");
setFocusable(true);
setBackgroundColor(Color.GREEN);
// setting paint
mPaint = new Paint();
mPaint.setAlpha(0);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mPaint.setAntiAlias(true);
// getting image from resources
Resources r = this.getContext().getResources();
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.foreground_image);
// converting image bitmap into mutable bitmap
bitmap = Bitmap.createBitmap(295, 260, Config.ARGB_8888);
pcanvas = new Canvas();
pcanvas.setBitmap(bitmap); // drawXY will result on that Bitmap
pcanvas.drawBitmap(bm, 0, 0, null);
}
#Override
protected void onDraw(Canvas canvas) {
// draw a circle that is erasing bitmap
pcanvas.drawCircle(x, y, r, mPaint);
canvas.drawBitmap(bitmap, 0, 0,null);
super.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// set paramete to draw circle on touch event
x = (int) event.getX();
y = (int) event.getY();
r =20;
// Atlast invalidate canvas
invalidate();
return true;
}
}
BASIC MAIN CLASS CALLING MAIN.XML
package com.easyscratch.full;
import android.app.Activity;
import android.os.Bundle;
public class easyscratch extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
,, If only Someone cud tell me what im doing wrong , or maybe an alternative implementation of the
public Panel(Context context) {
super(context);
anyway thanks alot in advanced really would appriciate some help as soon as possible :)
CHEERS GUYS!
Your constructor for Panel must also, at least, have an AttributeSet field.
public Panel(Context context, AttributeSet attr){
super.(context, attr);

Categories

Resources