I am having a little problem with my android project I hope I will find a fix from you guys.
I am getting an image from Phone gallery or take the pic from the front or rare camera and setting it in an ImageView. Everything is working fine that I can get the image from the gallery and can take the pic from the camera and set it in the image view.
Problem:
The problem I am facing is that the orientation of the image is not what I want. When I Capture a picture from Front camera of my mobile the image is shown Right to left not from top to Bottom. Please see the following image:
And when I capture an image in Portrait (from rare camera) it is shown as Left to right in the ImageView not from Top to bottom.
And when I capture the image in Landscape mode it is shown normal in the ImageView i-e From Top to Bottom.
this is the landscape mode image output..
I don't know how I fix it.. so what i am missing or what i should do to make all the images in the ImageView in Top to Bottom view.
Here are my XML and Java Files:
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imgProfilePic"
android:layout_above="#+id/btnGetPic"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnGetPic"
android:layout_alignParentBottom="true"
android:text="Get pictures from Gallery or Camera"/>
</RelativeLayout>
Java File :
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button btnGetPic;
ImageView imgProfilePic;
private static int REQUEST_GALLERY = 1;
private static int REQUEST_CAMERA = 2;
RoundTheImage roundedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetPic = (Button) findViewById(R.id.btnGetPic);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
btnGetPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bundle bundle = new Bundle();
bundle = data.getExtras();
Bitmap bmp;
bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
roundedImage = new RoundTheImage(resized);
imgProfilePic.setImageDrawable(roundedImage);
} else if (requestCode == REQUEST_GALLERY && null != data) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
Bitmap bmp;
bmp = BitmapFactory.decodeStream(inputStream);
Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
roundedImage = new RoundTheImage(resized);
imgProfilePic.setImageDrawable(roundedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo from Camera", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo from Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent,REQUEST_CAMERA); // 1 as REQUEST_CAMERA
}
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_GALLERY);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
And I use this Class to round the edges of the images (I get this one from one of SO answers)
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
public class RoundTheImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundTheImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
How to set Android camera orientation properly?
Have a look at that, it should answer your question. Essentially you need to tell the app what orientation the camera is in based on the phone sensor and that should allow you to capture in the correct orientation. Hope it helps!
Thanks to hipkiss for pointing me toward right direction.
Please note: This is not the best solution out there and it may not be well optimised and it may not work with every device.
For newcomers, like me, here is what my final code looked like. So it may help someone some day :)
First do this in your button's click event or in alert dialog etc
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_GALLERY);
declare
REQUEST_GALLERY as
private static int REQUEST_GALLERY = 1;
And now in your
onActivityResult Do something like this:
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
int rotation = getCameraPhotoOrientation(MainActivity.this,selectedImage,imgPath);
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap original = BitmapFactory.decodeFile(imgPath);
Bitmap myFinalImg = Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(), matrix, true);
ImageView imgView = (ImageView) findViewById(R.id.imgProfilePic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(myFinalImg);
} catch (Exception e) {
Toast.makeText(this, "Unable to load the image", Toast.LENGTH_LONG).show();
}
And this function will return the rotation ( that is how much rotation should be done)
public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
#Pros out there please fix/improve this answer so it may help other and let me know how i can improve it too :)
Edit:
Don't forget to add the permission in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Related
I have a null pointer exception when i load an image in my imageview. I have searched in so many topic but i not found a solution. I don't know why this won't work :/ Ahm another small bug, before i made an Imageview parameter in the class i try to use something like ImageView profilPicture = (ImageView) findViewById(R.id.profil_picture); but this produce an "error" android studio tell me to create the method...
So there is the error code :
Caused by: java.lang.NullPointerException
at android.graphics.BitmapShader.<init>(BitmapShader.java:40)
at god.repertoire.RoundImage.<init>(RoundImage.java:30)
at god.repertoire.FragmentNoContact.onActivityResult(FragmentNoContact.java:83)
There is the code of my Fragment :
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class FragmentNoContact extends Fragment {
private static int RESULT_LOAD_IMG = 1;
ImageView profilPicture;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// GET FRAGMENT COMPONENT
View myView = inflater.inflate(R.layout.activity_no_contact, container, false);
FloatingActionButton addContact = (FloatingActionButton) myView.findViewById(R.id.button_add);
profilPicture = (ImageView) myView.findViewById(R.id.profil_picture);
// INIT PHOTO DE PROFIL
Bitmap img = SaveLoad.loadFromFile("profil_picture.jpg");
if (img == null)
img = BitmapFactory.decodeResource(getResources(), R.drawable.blank_profile);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
// EVENT AU CLIC PHOTO
profilPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
/* an example i used before to test if i can set an another image
ImageView profilPicture = (ImageView) v.findViewById(R.id.profil_picture);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.me);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
*/
}
});
// ACTION BOUTON AJOUTER CONTACT
addContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
FragmentAddContact fragment2 = new FragmentAddContact();
transaction.add(R.id.myFrameLayout, fragment2);
transaction.addToBackStack("FragmentAddContact");
transaction.commit();
}
});
return myView;
}
// EVENT IMAGE SELECTED
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;//returning null for below statement
Bitmap img = BitmapFactory.decodeFile(selectedImage.toString(), options);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
}
}
}
There is the code of the RoundImage class (it's a class to generate a crop circle image in an imageView) :
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
public class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
And finaly, there is the code xml to create the imageview :
<ImageView
android:id="#+id/profil_picture"
android:layout_width="128dp"
android:layout_height="128dp"
android:scaleType="centerCrop"/>
Try this it may help you.
int id3 = getResources().getIdentifier("com.example.admin:mipmap/status" , null, null);
((ImageView) findViewById(R.id.imageviewstatus)).setImageResource(id3);
I am developing a photo-editor app. I have done horizontally and vertically flipping. Now, The problem is that When I choose horizontally flip option and do zoom then choose vertically flip option and do zoom and then I choose horizontally flip option again, Than left TouchImageView is misplaced, but right TouchImageView is in place. Below images explains much better.....
Step-1: Choose image from Gallery....
Step-2: Flip it horizontally....
Step-3: Zoom in horizontal flip....
Step-4: Flip it vertically....
Step-5: Zoom in vertical flip....
Step-6: Now back to horizontal flip....
Now, see step no 3 & 6. Step no.6 must be same as step no.3
What I have done is below.
Second.java
package com.MyFirstApp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.devsmart.android.ui.HorizontalListView;
public class Second extends Activity {
TouchImageView img_to_be_zoomedH, img_to_be_zoomed_secondH,
img_to_be_zoomedV, img_to_be_zoomed_secondV;
ImageView img_back, img_save;
HorizontalListView HListView, HListViewFirst;
/* Save Parent Layout After Editing */
RelativeLayout parentLayoutforImgSaving;
Bitmap bitmap_img, bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
img_to_be_zoomedH = (TouchImageView) findViewById(R.id.img_to_be_zoomedH);
img_to_be_zoomed_secondH = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondH);
img_to_be_zoomedV = (TouchImageView) findViewById(R.id.img_to_be_zoomedV);
img_to_be_zoomed_secondV = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondV);
img_back = (ImageView) findViewById(R.id.img_back_icon);
img_save = (ImageView) findViewById(R.id.img_save_icon);
HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);
parentLayoutforImgSaving = (RelativeLayout) findViewById(R.id.imagelayout);
/* Top Back Icon */
img_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
/* Save Image Icon */
img_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
saveImgAfterEditing(parentLayoutforImgSaving);
}
});
/* Left Image Touch Event */
img_to_be_zoomedH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondH.setZoom(img_to_be_zoomedH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedH.getScrollPosition();
img_to_be_zoomed_secondH.setScrollPosition(
1 - pointF_img1.x, pointF_img1.y);
}
});
/* Right Image touch event */
img_to_be_zoomed_secondH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedH.setZoom(img_to_be_zoomed_secondH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondH
.getScrollPosition();
img_to_be_zoomedH.setScrollPosition(1 - pointF_img1.x,
pointF_img1.y);
}
});
/* Top Image Touch Event */
img_to_be_zoomedV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondV.setZoom(img_to_be_zoomedV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedV.getScrollPosition();
img_to_be_zoomed_secondV.setScrollPosition(
pointF_img1.x, 1 - pointF_img1.y);
}
});
/* Bottom Image touch event */
img_to_be_zoomed_secondV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedV.setZoom(img_to_be_zoomed_secondV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondV
.getScrollPosition();
img_to_be_zoomedV.setScrollPosition(pointF_img1.x,
1 - pointF_img1.y);
}
});
int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
R.drawable.icon_text, R.drawable.icon_clip_art };
final int[] HorizontalListImagesFirst = new int[] {
R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
R.drawable.icon_vertical_grid };
/* Animation References */
final Animation slideUp = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_up);
final Animation slideDown = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_down);
/* Setting Adapter for Horizontal List Views */
HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
Second.this, HorizontalListImages);
HListView.setAdapter(horizontalListViewAdapter);
/* Horizontal List View Item Click Listener */
HListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
Second.this, HorizontalListImagesFirst);
HListViewFirst.setAdapter(horizontalListViewAdapterFirst);
HListView.startAnimation(slideDown);
HListView.setVisibility(View.GONE);
HListViewFirst.startAnimation(slideUp);
HListViewFirst.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
HListViewFirst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* HighLight Selected Option */
for (int i = 0; i < HListViewFirst.getChildCount(); i++) {
if (position == i) {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.GRAY);
} else {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
}
}
/* Get Device`s Height, Width */
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
switch (position) {
case 0:
HListViewFirst.startAnimation(slideDown);
HListViewFirst.setVisibility(View.GONE);
HListView.startAnimation(slideUp);
HListView.setVisibility(View.VISIBLE);
break;
case 1:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams1 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams1);
/* Setting Left ImageView width, height */
RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsLeft.setMargins(0, 0, 0, 0);
img_to_be_zoomedH.setLayoutParams(layoutParamsLeft);
img_to_be_zoomedH.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedH
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 2);
img_to_be_zoomed_secondH.setImageBitmap(bitmap_img);
/* Setting Right ImageView width, height */
RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsRight.setMargins(width / 2, 0, 0, 0);
img_to_be_zoomed_secondH.setLayoutParams(layoutParamsRight);
// img_to_be_zoomedH.invalidate();
img_to_be_zoomed_secondH.setVisibility(view.VISIBLE);
/* Hiding Vertical TouchIMageViews */
if ((img_to_be_zoomedV.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondV.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedV.setVisibility(view.GONE);
img_to_be_zoomed_secondV.setVisibility(view.GONE);
}
break;
case 2:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams2 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams2);
/* Setting Top ImageView width, height */
RelativeLayout.LayoutParams layoutParamsTop = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsTop.setMargins(0, 0, 0, 0);
img_to_be_zoomedV.setLayoutParams(layoutParamsTop);
img_to_be_zoomedV.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedV
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 1);
img_to_be_zoomed_secondV.setImageBitmap(bitmap_img);
/* Setting Bottom ImageView width, height */
RelativeLayout.LayoutParams layoutParamsBottom = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsBottom.setMargins(0, width / 2, 0, 0);
img_to_be_zoomed_secondV
.setLayoutParams(layoutParamsBottom);
// img_to_be_zoomedV.invalidate();
img_to_be_zoomed_secondV.setVisibility(view.VISIBLE);
/* Hiding Horizontal TouchIMageViews */
if ((img_to_be_zoomedH.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondH.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedH.setVisibility(view.GONE);
img_to_be_zoomed_secondH.setVisibility(view.GONE);
}
break;
default:
break;
}
}
});
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri != null) {
String[] selectedImgPath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImgUri,
selectedImgPath, null, null, null);
cursor.moveToFirst();
int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
String imgPath = cursor.getString(indexCol);
cursor.close();
img_to_be_zoomedH.setImageBitmap(BitmapFactory.decodeFile(imgPath));
img_to_be_zoomedV.setImageBitmap(BitmapFactory.decodeFile(imgPath));
}
/* Getting ImageBitmap from Camera from Main Activity */
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("BitmapImage");
if (camera_img_bitmap != null) {
img_to_be_zoomedH.setImageBitmap(camera_img_bitmap);
img_to_be_zoomedV.setImageBitmap(camera_img_bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Flip Image Function */
public Bitmap flipImage(Bitmap src, int type) {
Matrix matrix = new Matrix();
/* Flip vertically */
if (type == 1) {
matrix.preScale(1.0f, -1.0f);
/* Flip horizontally */
} else if (type == 2) {
matrix.preScale(-1.0f, 1.0f);
} else {
return null;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/* Save Image Function */
private void saveImgAfterEditing(RelativeLayout perent) {
try {
View content = parentLayoutforImgSaving;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/" + getString(R.string.app_name));
if (!mFolder.exists()) {
mFolder.mkdir();
}
Calendar c = Calendar.getInstance();
String s = getString(R.string.app_name) + c.getTimeInMillis()
+ ".png";
File f = new File(mFolder.getAbsolutePath(), s);
FileOutputStream fos = null;
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bitmap.recycle();
Toast.makeText(getBaseContext(), "Image Saved", 5000).show();
addImageGallery(f);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Failed To Save", 5000).show();
e.printStackTrace();
}
}
/* Save Image to Direct Gallery, No Need to Refresh */
private void addImageGallery(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.MyFirstApp.myfirstapp.Second" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<ImageView
android:id="#+id/img_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="#string/img_back_icon"
android:src="#drawable/icon_back" />
<TextView
android:id="#+id/txtview_app_name_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/txtview_app_name_top" />
<ImageView
android:id="#+id/img_save_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/img_save_icon"
android:src="#drawable/icon_save" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedH"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="23dp"
android:src="#drawable/home" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view"
android:layout_width="wrap_content"
android:layout_height="40dp" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_first"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:choiceMode="singleChoice"
android:listSelector="#drawable/horizontal_list_view_selector"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
Thanks in advance.
I am trying to implement "Upload Profile Pic" thing in the android. Below is the Snapshot which I need to Implement in the Android.
Snapshot_for_profile_page.png
I want "Add Photo" to work like same as Instagram's Edit profile thing.
Here's What I have done so far.
I took ImageButton.
Onlcick event i uploaded the picture either from Camera/Gallery.
But the problem is that image which is being uploaded gets squared.
Also How to resize the image to fit within that circle. I want full image to get exactly fit into the circle. Just like on Instagram
Here is my code
Profile.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Profile extends FragmentActivity {
private ImageButton mProfileImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_activity);
mProfileImage = (ImageButton) findViewById(R.id.imageButton);
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if(options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
mProfileImage.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Phoenix" + File.separator + "default";
f. delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
mProfileImage.setImageBitmap(thumbnail);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_profile, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
profile_activity.xml
<ImageButton
android:layout_width="150dp"
android:layout_height="155dp"
android:id="#+id/imageButton"
android:src="#drawable/add_photo"
android:background="#drawable/circlebutton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
circlebutton.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FFFFFF"/>
<stroke android:width="1dp" android:color="#00A2B3" />
<!--<corners
android:bottomLeftRadius="12.0dip"
android:bottomRightRadius="12.0dip"
android:radius="12.0dip"
android:topLeftRadius="12.0dip"
android:topRightRadius="12.0dip" />-->
</shape>
The button is still in the form of square.
PS: Sorry for my English
I recommend you to use Picasso library. Make a class that extends the Transformation class of Picasso.
public class RoundTransformation implements com.squareup.picasso.Transformation {
private final int radius;
private final int margin;
public RoundTransformation(final int radius, final int margin) {
this.radius = radius;
this.margin = margin;
}
#Override
public Bitmap transform( Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
#Override
public String key() {
return "rounded";
}
}
Once you have this class ready. Use the Picasso library
Picasso.with(context).load("url")
.transform(new RoundTransformation(radius,margin)).into(image);
PS : Instead of Using an ImageButton use ImageView and use a setOnClickListener on the imageview
Just a trick that is completely different than your solution,
Let the image remain square or whatever. Just center it inside its parent.
Place another white imageView with a bordered circular space in the center overlying that profile picture.
This is called masking :)
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.
Im having problem integrating method for scaling images thru method on animate slide show. My goal is i have 10 large images that i will us for slide show, when i try to test 2 images its working perfectly, but when i try to use all the images it gives me error java.lang.OutOfMemoryError: bitmap size exceeds VM budget, i search on the internet, i came up to scale the images or use bitmap, several codes i got, but my problem is that how can i integrate the bitmap/decode codes that i got from the net to my slideshow script.
below is the script:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SliderActivity extends Activity {
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingImage;
private int[] IMAGE_IDS = {
R.drawable.pic1edited, R.drawable.pic2edited, R.drawable.pic3edited,
R.drawable.pic4edited, R.drawable.pic5edited
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set fullscreen and no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_slider);
Bitmap image = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier( "imagename" , "drawable", getPackageName()));
final Handler mhandler = new Handler();
//Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
#Override
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; //delay for 1 sec
int period = 8000; //repeat every 4 sec
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mhandler.post(mUpdateResults);
}
}, delay, period);
}
//Helper method to start the animation on the splash screen
private void AnimateandSlideShow() {
slidingImage = (ImageView)findViewById(R.id.imageView1);
slidingImage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
slidingImage.setAnimation(rotateimage);
Log.d(getClass().getName(), "value = " + currentimageindex);
}
private Drawable resize(Drawable image) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 50, 50, false);
return new BitmapDrawable(bitmapResized);
}
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//override some buttons
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Log.d("button", new Integer(keyCode).toString());
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_CALL)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_MENU)) {
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}