moving a ball with help of accelerometer in android - java

I had written a code to move a ball with the help of accelerometer in android such that if it touches any of 4 edges it reappears on opposide edge my problems are
1.ball is not reappearing on opposite edge
2.orientation changes to lanscape
here is my code
public class Accelerate extends Activity implements SensorEventListener {
float x, y, sensorX, sensorY, a, b, centerX, centerY;
Bitmap ball;
SensorManager sm;
NixSurface ourSurfaceView;
public class NixSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public NixSurface(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(255, 255, 255);
centerX = canvas.getWidth() / 2;
centerY = canvas.getHeight() / 2;
x += sensorX;
y += sensorY;
a = centerX + x;
b = centerY + y;
if (a > canvas.getWidth())
a = 0;
if (b > canvas.getHeight())
b = 0;
if (a < 0)
a = canvas.getWidth();
if (b < 0)
b = canvas.getHeight();
canvas.drawBitmap(ball, a, b, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
x = y = sensorY = sensorX = 0;
ball = BitmapFactory.decodeResource(getResources(), R.drawable.nix);
ourSurfaceView = new NixSurface(this);
ourSurfaceView.resume();
setContentView(ourSurfaceView);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
// nothing to do here
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sensorX = -event.values[0];
sensorY = event.values[1];
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}

I guess your problem is that you assume that the sensor origin (x=0,y=0) is the screen center. The sensor origin is the top left corner of the screen (X pointing left and Y pointing down), so comparing a & b to canvas.getWidth() & canvas.getHeight() is not correct since you already added centerX & centerY. Also, negating sensorX will cause the condition a > canvas.getWidth() to never occur since X is never negative.

Related

seekbar using first 0.12 and 0.13 combination adding the value

seekbar using volume increment and decrement for 0.12 and 0.13 combination like 0.12,0.25,0.37,0.50,0.62,0.75,0.87 but i getting values like this 0.12,0.25,0.38,0.50,0.62,0.75,0.88 .Please suggest me how can i clear the issues.
public class MainActivity extends Activity {
Button b1;
SeekBar sk1;
double point=0.12;
double value=0.00;
int previous=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
sk1=(SeekBar) findViewById(R.id.seekBar1);
sk1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
// TODO Auto-generated method stub
int p = progress;
double f = progress;
double x = Double.parseDouble(b1.getText().toString());
if (point == 0.12)
{
if (previous > p)
{
if (x == -20.00 )
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value - a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
else if (previous < p)
{
if (x == 20.00)
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value + a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
}
previous = progress;
}
});
}

Null Pointer Exception with "getPackageName()"

I have been stuck on this problem for the past week and a half. I made a game using the "Kilobolt" framework, and I have been trying to implement in App Purchase's in my app and i've tried every way possible but I keep getting the same error, that there is a null pointer exception.
06-13 21:40:18.991: E/AndroidRuntime(16384): java.lang.NullPointerException
06-13 21:40:18.991: E/AndroidRuntime(16384): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
I have 1 activity where I have my method levelTwoButtonClicked() and I am calling that method from a java class, this is where the null pointer exception is coming from and it is because of getPackageName().
I have this in a try catch statement:
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);.
I have done some research and I read that there could be a issue with the context and calling getPackageName() but havent been able to figure out the issue yet thanks for any one who can help me resolve this!
public abstract class AndroidGame extends Activity implements Game {
public static Context mContext;
IInAppBillingService mService;
ServiceConnection mServiceConn;
static final String ITEM_SKU = "android.test.purchased";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int frameBufferWidth = isPortrait ? 480: 800;
int frameBufferHeight = isPortrait ? 800: 480;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(renderView);
setContentView(layout);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
mContext = getBaseContext();
mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
public void levelTwoButtonClicked(){
Assets.click.play(1.00f);
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("android.test.purchased");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals("android.test.purchased")) {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (SendIntentException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("android.test.purchased");
Toast.makeText(mContext,"You have bought the " + sku + ". Excellent choice,adventurer!", Toast.LENGTH_LONG).show();
}
catch (JSONException e) {
Toast.makeText(mContext,"Failed to parse purchase data.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
public static Context getContext(){
return mContext;
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
screen.resume();
renderView.resume();
mAdView.resume();
if(Assets.mainmenuloop.isStopped()){
Assets.mainmenuloop.play();
}
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
renderView.pause();
screen.pause();
mAdView.pause();
if(Assets.mainmenuloop.isPlaying()){
Assets.mainmenuloop.stop();
}
SharedPreferences HighScoreData = getSharedPreferences("high", 0);
SharedPreferences.Editor editor = HighScoreData.edit();
editor.putInt("score", highScore);
editor.putInt("secondScore", secondHighScore);
editor.putInt("thirdScore", thirdHighScore);
editor.putInt("fourthScore", fourthHighScore);
editor.commit();
if (isFinishing())
screen.dispose();
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
return graphics;
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void onDestroy() {
super.onDestroy();
mAdView.destroy();
/*
if (mService != null) {
unbindService(mServiceConn);
}
*/
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
public Screen getCurrentScreen() {
return screen;
}
}
// END OF ACTIVITY CLASS
// BEGIN REGULAR JAVA CLASS
public class InAppPurchase extends Screen {
AndroidGame Buy = new PurchaseLevels();
public InAppPurchase(Game game) {
super(game);
}
#Override
public void update(float deltaTime) {
// TODO Auto-generated method stub
#SuppressWarnings("unused")
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
if(inBounds(event, 195, 142, 235, 55)) {
// UNLOCK LEVEL TWO
Buy.levelTwoButtonClicked();
}
if(inBounds(event, 195, 310, 235, 55)) {
// UNLOCK LEVEL THREE
}
if(inBounds(event, 195, 490, 235, 55)) {
// UNLOCK LEVEL FOUR
}
if(inBounds(event, 70, 630, 210, 55)) {
// RESTORE BUTTON
Assets.click.play(1.00f);
}
if(inBounds(event, 330, 635, 130, 130)) {
game.setScreen(new MainMenuScreen(game));
Assets.click.play(1.00f);
}
}
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width,
int height) {
if (event.x > x && event.x < x + width - 1 && event.y > y
&& event.y < y + height - 1){
return true;
} else {
return false;
}
}
public void updateUI(){
}
#Override
public void paint(float deltaTime) {
// TODO Auto-generated method stub
}
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public void backButton() {
// TODO Auto-generated method stub
}
}
// MAIN ACTIVITY SUBCLASS HAD TO MAKE THIS TO CREATE AN INSTANCE OF MY ABSTRACT MAIN ACTIVITY "ANDROIDGAME" IN MY IN APP PURCHASE CLASS, IN ORDER TO CALL "LEVELTWOBUTTONCLICKED"
public class PurchaseLevels extends AndroidGame {
#Override
public Screen getInitScreen() {
// TODO Auto-generated method stub
return null;
}
}

Android java | Suttering and lags when updating View layout params

Recently I'm making a game which requires continuous animation.
I'll explain it further.
I got view let's say top of the screen and I need to animate it from the top of the screen to the bottom of the screen and then it will go back to the original spot (Top of the screen) when the view is on the bottom.
Now there's 6 views which does the exactly same thing.
Animate from top of the screen to the bottom of the screen and back when they are on the bottom.
But when they are already moving there's really annoying stuttering and lags on the application.
Here's the code :
#Override
public void onWindowFocusChanged(boolean focus) {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!failedM) {
running = true;
soundPool.play(click_sound, 1, 1, 0, 0, 1);
play.setVisibility(View.INVISIBLE);
p1.setVisibility(View.VISIBLE);
p2.setVisibility(View.VISIBLE);
p3.setVisibility(View.VISIBLE);
c1.setVisibility(View.VISIBLE);
c2.setVisibility(View.VISIBLE);
c3.setVisibility(View.VISIBLE);
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.post(new Runnable() {
#Override
public void run() {
p1.getHitRect(rect1);
p2.getHitRect(rect2);
p3.getHitRect(rect3);
c1.getHitRect(rect4);
c2.getHitRect(rect5);
c3.getHitRect(rect6);
if (Rect.intersects(rect, rect1)
{
.....
}
if (Rect.intersects(rect, rect2)
) {
.....
}
if (Rect.intersects(rect, rect3)
) {
.....
}
if (Rect.intersects(rect, rect4)
) {
.....
}
if (Rect.intersects(rect, rect5)
) {
.....
}
if (Rect.intersects(rect, rect6)
) {
.....
}
downy1 += 1;
downy2 += 1;
downy3 += 1;
downy4 += 1;
downy5 += 1;
downy6 += 1;
params1.topMargin = params1.topMargin
+ downy1;
params2.topMargin = params2.topMargin
+ downy2;
params3.topMargin = params3.topMargin
+ downy3;
params4.topMargin = params4.topMargin
+ downy4;
params5.topMargin = params5.topMargin
+ downy5;
params6.topMargin = params6.topMargin
+ downy6;
p1.setLayoutParams(params1);
p2.setLayoutParams(params2);
p3.setLayoutParams(params3);
c1.setLayoutParams(params4);
c2.setLayoutParams(params5);
c3.setLayoutParams(params6);
if (p1.getTop() > height) {
downy1 = 0;
params1.leftMargin = newX;
params1.topMargin = orig1y;
p1.setLayoutParams(params1);
}
if (p2.getTop() > height) {
downy2 = 0;
params2.leftMargin = newX;
params2.topMargin = orig2y;
p2.setLayoutParams(params2);
}
if (p3.getTop() > height) {
downy3 = 0;
params3.leftMargin = newX;
params3.topMargin = orig3y;
p3.setLayoutParams(params3);
}
if (c1.getTop() > height
&& !failedM) {
downy4 = 0;
params4.leftMargin = newX;
params4.topMargin = orig4y;
c1.setLayoutParams(params4);
}
if (c2.getTop() > height
&& !failedM) {
downy5 = 0;
params5.leftMargin = newX;
params5.topMargin = orig5y;
c2.setLayoutParams(params5);
}
if (c3.getTop() > height
&& !failedM) {
downy6 = 0;
params6.leftMargin = newX;
params6.topMargin = orig6y;
c3.setLayoutParams(params6);
}
}
});
}
}
}).start();
}
});
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
As you can see there's (if view.getTop() > height)
What it means is that when the view Y is bigger than the height which is when the view is moving from the top to the bottom it will go back to the top.
I hope I made it clear
Thanks in advance.
You should use the animation framework. (view.animate()...).
Setting layout params requires re-calculating the layout, which is potentially not a cheap operation (depends on your layout).
You can use animation framework or set translateX/Y etc properties of the view, which avoid re-calculating the layout.

Fatal Exception On going back to menu

So Im doing a little up, not a big deal, just learning graphics, but when i click on the back button, the app crashes and it gives me fatal error 11.
Code:
public class MyPachuSurface extends SurfaceView implements Runnable{
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = false;
public float x,y,startX,startY,finalX,finalY,dx,dy,tx,ty;
public MyPachuSurface(Context context)
{
super(context);
// TODO Auto-generated constructor stub
myHolder = getHolder();
this.x = 0;
this.y = 0;
this.startX = 0;
this.startY = 0;
this.finalX = 0;
this.finalY = 0;
this.dx = 0;
this.dy = 0;
this.tx = 0;
this.ty = 0;
}
public void pause()
{
isRunning = false;
try
{
myThread.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myThread = null;
}
public void resume ()
{
isRunning = true;
myThread = new Thread(this);
myThread.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(isRunning)
{
if(!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawRGB(02, 02, 254);
if(this.x != 0 && this.y != 0)
{
Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.plus1);
canvas.drawBitmap(test, this.x - test.getWidth()/2 - this.tx, this.y - test.getHeight()/2 - this.ty, null);
this.tx += this.dx/30;
this.ty += this.dy/30;
}
myHolder.unlockCanvasAndPost(canvas);
}
}
}
This is the view, and this is the activity :
public class MyGraphicsSurface extends Activity implements OnTouchListener{
MyPachuSurface pachuSurf;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
pachuSurf = new MyPachuSurface(this);
pachuSurf.setOnTouchListener(this);
setContentView(pachuSurf);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pachuSurf.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pachuSurf.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
this.pachuSurf.x = event.getX();
this.pachuSurf.y = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
pachuSurf.startX = event.getX();
pachuSurf.startY = event.getY();
pachuSurf.tx = 0;
pachuSurf.ty = 0;
break;
case MotionEvent.ACTION_UP:
pachuSurf.finalX = event.getX();
pachuSurf.finalY = event.getY();
pachuSurf.dx = pachuSurf.finalX - pachuSurf.startX;
pachuSurf.dy = pachuSurf.finalY - pachuSurf.startY;
break;
}
return true;
}
}
And This is The Loc Cat:
06-06 17:37:20.104: E/AndroidRuntime(22781): FATAL EXCEPTION: Thread-29865
06-06 17:37:20.104: E/AndroidRuntime(22781): java.lang.NullPointerException
06-06 17:37:20.104: E/AndroidRuntime(22781): at com.example.myfirstapp.MyPachuSurface.run(MyPachuSurface.java:68)
06-06 17:37:20.104: E/AndroidRuntime(22781): at java.lang.Thread.run(Thread.java:856)

Not able to draw in my drawing ANDROID APP

I am developing an Android drawing app.
When I run this code it says application is doing too much work on it's main thread in logcat.I am not able to draw.PLEASE HELP ME.Thank you
THIS IS MY DRAWIT CLASS
public class Drawit extends Activity {
LinearLayout linearLayout;
ImageButton oclear,save,ocancel;
View mview;
DrawCanvas drawCanvas;
public static String tempDir;
public static String unique_id;
public static String current=null;
public Bitmap mBitmap;
public EditText yourName;
File myPath;
protected void onCreate(Bundle savedInsatnceState) {
// TODO Auto-generated method stub
super.onCreate(savedInsatnceState);
setContentView(R.layout.drawit);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout11);
tempDir = Environment.getExternalStorageDirectory()+"/"+getResources().getString(R.string.external_dir);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir(getResources().getString(R.string.external_dir),MODE_PRIVATE);
preparedirectory();
yourName = (EditText) findViewById(R.id.editText1);
myPath = new File(directory,current);
drawCanvas = new DrawCanvas(this, null);
drawCanvas.setBackgroundColor(Color.WHITE);
linearLayout.addView(drawCanvas,LayoutParams.FILL_PARENT);
}
}
THIS IS MY DRAW CANVAS METHOD
public class DrawCanvas extends View
{
public Paint paint = new Paint();
public Path path = new Path();
public final RectF dirtyRect = new RectF();
public float lastTouchX;
public float lastTouchY;
public DrawCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5f);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setAntiAlias(true);
}
protected void ondraw(Canvas canvas) {
canvas.drawPath(path,paint);
}
public void save(View mview) throws IOException{
// TODO Auto-generated method stub
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap(linearLayout.getWidth(),linearLayout.getHeight(),Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream fileoutputstream = new FileOutputStream(myPath);
mview.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG , 90, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
String uri = Images.Media.insertImage(getContentResolver(),mBitmap,"title",null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clear() {
// TODO Auto-generated method stub
path.reset();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX,eventY);
int historyRectSize = event.getHistorySize();
for(int i=0;i<historyRectSize;i++)
{
float historicalx = event.getHistoricalX(i);
float historicaly = event.getHistoricalY(i);
expandDirtyRect(historicalx,historicaly);
path.lineTo(historicalx, historicaly);
}
break;
}
return true;
}
private void expandDirtyRect(float historicalx, float historicaly) {
// TODO Auto-generated method stub
if(historicalx < dirtyRect.left)
{
dirtyRect.left = historicalx;
} else if(historicalx >dirtyRect.right)
{
dirtyRect.left = historicalx;
}
if(historicaly < dirtyRect.top)
{
dirtyRect.top = historicaly;
} else if(historicaly >dirtyRect.bottom)
{
dirtyRect.bottom = historicaly;
}
}
private void resetDirtyRect(float eventX, float eventY) {
// TODO Auto-generated method stub
dirtyRect.left = Math.min(lastTouchX,eventX);
dirtyRect.right = Math.max(lastTouchX,eventX);
dirtyRect.top = Math.min(lastTouchY,eventY);
dirtyRect.bottom = Math.max(lastTouchY,eventY);
}
}
}

Categories