pick image from gallery error when setDrawable - android

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);

Related

how to pass the list of lists means List<List<Bitmap>> through bundle to the fragment in android

basically i working with fragments and i pass the List to the fragment by creating constructor but when i try to generate the signed apk file i got the error like
(This fragment should have a default constructor) after searching i find the method to create the newInstance to to pass the data to another fragment by bundle
like this...
public static Fragment newInstance(String arg1, int arg2) {
Fragment result = new MyFragment();
Bundle args = new Bundle();
args.putString("arg1_key", arg1);
args.putInt("arg2_key", arg2);
result.setArguments(args);
return result;
}
And my code is here please any suggestion.......
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.internal.ParcelableSparseArray;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import com.google.android.gms.ads.AdView;
import com.nhaarman.listviewanimations.appearance.simple.AlphaInAnimationAdapter;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import java.util.ArrayList;
import java.util.List;
/**
* Created by waqar on 12/01/2017.
*/
public class splashFragment extends Fragment {
private int[] HandImages = {R.drawable.hands_1, R.drawable.hands_2, R.drawable.hands_3, R.drawable.hands_4, R.drawable.hands_5,
R.drawable.hands_6, R.drawable.hands_7, R.drawable.hands_8, R.drawable.hands_9, R.drawable.hands_10,
R.drawable.hands_11, R.drawable.hands_12, R.drawable.hands_13, R.drawable.hands_14, R.drawable.hands_15,
R.drawable.foot_15};
private int[] FootImages = {R.drawable.foot_1, R.drawable.foot_2, R.drawable.foot_3, R.drawable.foot_4, R.drawable.foot_5,
R.drawable.foot_6, R.drawable.foot_7, R.drawable.foot_8, R.drawable.foot_9, R.drawable.foot_10,
R.drawable.foot_11, R.drawable.foot_12, R.drawable.foot_13, R.drawable.foot_14,
R.drawable.foot_15};
private int[] TatooImages = {R.drawable.tatoos_1, R.drawable.tatoos_2, R.drawable.tatoos_3, R.drawable.tatoos_4, R.drawable.tatoos_5,
R.drawable.tatoos_6, R.drawable.tatoos_7, R.drawable.tatoos_8, R.drawable.tatoos_9, R.drawable.tatoos_10, R.drawable.tatoos_11};
private int[] NailImages = {R.drawable.nail_1, R.drawable.nail_2, R.drawable.nail_3, R.drawable.nail_4, R.drawable.nail_5,
R.drawable.nail_6, R.drawable.nail_7, R.drawable.nail_8, R.drawable.nail_9, R.drawable.nail_10, R.drawable.nail_11};
ArrayList<Bitmap> HandsBitmapArray = new ArrayList<Bitmap>();
ArrayList<Bitmap> FootBitmapArray = new ArrayList<Bitmap>();
ArrayList<Bitmap> TatooBitmapArray = new ArrayList<Bitmap>();
ArrayList<Bitmap> NailBitmapArray = new ArrayList<Bitmap>();
ImageView imageView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.splash_fragment, container, false);
imageView = (ImageView) view.findViewById(R.id.imageView);
Picasso.with(getActivity()).load(R.drawable.design_12).transform(new CircleTransform()).into(imageView);
final AdView mAdView = (AdView) getActivity().findViewById(R.id.adView1);
mAdView.setVisibility(View.GONE);
if (HandImages != null && HandImages.length > 0) {
new BackGroundTask().execute();
}
return view;
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
float radius = size / 2f;
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.drawCircle(radius, radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
#Override
public String key() {
return "circle";
}
}
public class BackGroundTask extends AsyncTask<Object, Object, List<List<Bitmap>>> {
ProgressDialog progressDialog;
List<List<Bitmap>> arrayOfLists = new ArrayList<List<Bitmap>>();
#Override
protected void onPreExecute() {
super.onPreExecute();
/*progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();*/
}
/*#Override
protected void onProgressUpdate(Integer... values) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(values[0]);
}*/
#Override
protected List<List<Bitmap>> doInBackground(Object... params) {
if (isAdded() == true) {
for (int i = 0; i < HandImages.length; i++) {
Bitmap handsImaes = BitmapFactory.decodeResource(getActivity().getResources(), HandImages[i]);
/* int bytes = byteSizeOf(largeIcon);
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
largeIcon.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
byte[] array = buffer.array();*/
/* Bitmap b1 = BitmapFactor y.decodeByteArray(b, 0, b.length);
Bitmap bitmap = Bitmap.createScaledBitmap(b1, 120, 120, false);*/
//Bitmap bitmap = Bitmap.createScaledBitmap(largeIcon, 80, 80, true);
Bitmap HandBitmaps = getResizedBitmap(handsImaes, 80, 80);
//Bitmap bitmap = Bitmap.createScaledBitmap(largeIcon,(int)(largeIcon.getWidth()*0.1), (int)(largeIcon.getHeight()*0.1), true);
//Bitmap bitmap = scaleBitmap(largeIcon, 80, 80);
// Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), images[i], 80, 80);
HandsBitmapArray.add(HandBitmaps);
}
arrayOfLists.add(HandsBitmapArray);
for (int i = 0; i < FootImages.length; i++){
Bitmap footImages = BitmapFactory.decodeResource(getActivity().getResources(), FootImages[i]);
Bitmap FootBitmaps = getResizedBitmap(footImages, 80, 80);
FootBitmapArray.add(FootBitmaps);
}
arrayOfLists.add(FootBitmapArray);
for (int i = 0; i < TatooImages.length; i++){
Bitmap footImages = BitmapFactory.decodeResource(getActivity().getResources(), TatooImages[i]);
Bitmap FootBitmaps = getResizedBitmap(footImages, 80, 80);
TatooBitmapArray .add(FootBitmaps);
}
arrayOfLists.add(TatooBitmapArray);
for (int i = 0; i < NailImages.length; i++){
Bitmap footImages = BitmapFactory.decodeResource(getActivity().getResources(), NailImages[i]);
Bitmap FootBitmaps = getResizedBitmap(footImages, 80, 80);
NailBitmapArray .add(FootBitmaps);
}
arrayOfLists.add(NailBitmapArray);
}
return arrayOfLists;
}
#Override
protected void onPostExecute(final List<List<Bitmap>> result) {
super.onPostExecute(result);
//progressDialog.dismiss();
/*new CountDownTimer(2000, 800) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {*/
//MainFragment mainFragment = newInstance(result);
MainFragment mainFragment = new MainFragment(result);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
fragmentTransaction.replace(R.id.frame_lay, mainFragment, "mainFragment");
fragmentTransaction.commit();
/*}
}.start();*/
/*CustomAdapter adapter = new CustomAdapter(getActivity(), R.layout.custom_grid_row, result);
AlphaInAnimationAdapter swingRightInAnimationAdapter = new AlphaInAnimationAdapter(adapter);
swingRightInAnimationAdapter.setAbsListView(grid);
grid.setAdapter(swingRightInAnimationAdapter);*/
}
}
public static MainFragment newInstance(List<List<Bitmap>> bitmapArray)
{
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("array", bitmapArray);
fragment.setArguments(bundle);
return fragment;
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
/* BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inSampleSize = 6;*/
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
}
And my error in in this function......
public static MainFragment newInstance(List<List<Bitmap>> bitmapArray)
{
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("array", bitmapArray);
fragment.setArguments(bundle);
return fragment;
}
Edit my getterSetter class i like...
public class GetterSetterForBitmaps {
public List<List<Bitmap>> HandsList;
public List<List<Bitmap>> FootsList;
public List<List<Bitmap>> TatoosLists;
public List<List<Bitmap>> NailsLists;
public List<List<Bitmap>> getHandsList() {
return HandsList;
}
public void setHandsList(List<List<Bitmap>> handsList) {
HandsList = handsList;
}
public List<List<Bitmap>> getFootsList() {
return FootsList;
}
public void setFootsList(List<List<Bitmap>> footsList) {
FootsList = footsList;
}
public List<List<Bitmap>> getTatoosLists() {
return TatoosLists;
}
public void setTatoosLists(List<List<Bitmap>> tatoosLists) {
TatoosLists = tatoosLists;
}
public List<List<Bitmap>> getNailsLists() {
return NailsLists;
}
public void setNailsLists(List<List<Bitmap>> nailsLists) {
NailsLists = nailsLists;
}
}
and setting the list in GetterSetter like this..
GetterSetterForBitmaps getterSetterForBitmaps = new GetterSetterForBitmaps();
getterSetterForBitmaps.setHandsList(arrayOfLists);
but when get the list from GetterSetter like this...
GetterSetterForBitmaps getterSetterForBitmaps = new GetterSetterForBitmaps();
List<List<Bitmap>> list = getterSetterForBitmaps.getHandsList();
it returns null???
Don't do this, you will be wasting great amount of memory in
serializing and de-serializing bitmaps as it will create two
additional copies of same object and will cost you in longer run.
I would suggest rather create a DataLayer for passing data among Android Components
For example
class MyImageCache
{
static List<List<BitMap>> list;
public static getList(){
return list;
}
public static setList(List<List<BitMap>> list1){
list=list1;
}
}
This would save you from creating multiple copies of same object across app.
You can modify "ImageCache" class's behavior to have more control over data sharing.

Images not showing Properly in the ImageView

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"/>

How to clear canvas in a surface view?

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

Changing dragshadow in android, while dragging happens

Faced the problem of letting the dragshaddow (created by a DragShadowBuilder) react on something, while dragging is happening.
Do someone know how it supposed to be done?
Here's my complete code for custom drag shadow builder (gist for custom drag shadow).
However, as others stated there is no possibility to modify drag shadow using native functionality introduced in API-11.
package com.marcingil.dragshadow;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
public class ImageDragShadowBuilder extends View.DragShadowBuilder {
private Drawable shadow;
private ImageDragShadowBuilder() {
super();
}
public static View.DragShadowBuilder fromResource(Context context, int drawableId) {
ImageDragShadowBuilder builder = new ImageDragShadowBuilder();
builder.shadow = context.getResources().getDrawable(drawableId);
if (builder.shadow == null) {
throw new NullPointerException("Drawable from id is null");
}
builder.shadow.setBounds(0, 0, builder.shadow.getMinimumWidth(), builder.shadow.getMinimumHeight());
return builder;
}
public static View.DragShadowBuilder fromBitmap(Context context, Bitmap bmp) {
if (bmp == null) {
throw new IllegalArgumentException("Bitmap cannot be null");
}
ImageDragShadowBuilder builder = new ImageDragShadowBuilder();
builder.shadow = new BitmapDrawable(context.getResources(), bmp);
builder.shadow.setBounds(0, 0, builder.shadow.getMinimumWidth(), builder.shadow.getMinimumHeight());
return builder;
}
#Override
public void onDrawShadow(Canvas canvas) {
shadow.draw(canvas);
}
#Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
shadowSize.x = shadow.getMinimumWidth();
shadowSize.y = shadow.getMinimumHeight();
shadowTouchPoint.x = (int)(shadowSize.x / 2);
shadowTouchPoint.y = (int)(shadowSize.y / 2);
}
}

Android: attempting to draw a canvas on a relative layout and eclipse wants to initialise a variable that shouldn't need it

Hello EclipeE wants to initialise:
CustomDrawableView mCustomDrawableView;
Any ideas?
Cheers
Phil
Here's my code:
package com.android.phil.graphtoggle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
public class MainActivity extends Activity
{
public int graph_toggle = 0;
public int data_toggle=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton graph_toggle_button = (ImageButton) findViewById(R.id.graph_toggle);
final ImageButton graph_settings_button = (ImageButton) findViewById(R.id.graph_type);
final ImageButton data_toggle_button = (ImageButton) findViewById(R.id.data_toggle);
CustomDrawableView mCustomDrawableView;
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relativeLayout1);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,200);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// add here other layout params rules to make your
// custom view stay below the buttons
mCustomDrawableView.setLayoutParams(lp);
mainLayout.addView(mCustomDrawableView);
graph_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (graph_toggle==2)
{
graph_toggle=0;
}
else
{
graph_toggle++;
}
if (graph_toggle==0)
{
graph_settings_button.setImageResource(R.drawable.close);
}
if (graph_toggle==1)
{
graph_settings_button.setImageResource(R.drawable.ohlc_bars);
}
if(graph_toggle==2)
{
graph_settings_button.setImageResource(R.drawable.candles);
}
}
});
data_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (data_toggle==2)
{
data_toggle=0;
}
else
{
data_toggle++;
}
if (data_toggle==0)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_daily);
}
if (data_toggle==1)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_weekly);
}
if(data_toggle==2)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_monthly);
}
}
});
}
public class CustomDrawableView extends View
{
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context)
{
super(context);
int x = 10;
int y = 100;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas)
{
mDrawable.draw(canvas);
}
}
}
You aren't initializing mCustomDrawableView anywhere so mCustomDrawableView.setLayoutParams(lp); is going to cause a NullPointerException.
You are missing something like
mCustomDrawableView = (CustomDrawableView) this.findViewById(R.id.my_custom_view);

Categories

Resources