In Android, when rotate the image it slowly dissappear. - android

I used the the below code to rotate the image. There is no problem in image rotation, but when i rotate the image the image pixels was reduced. if i rotate continuously means the image will disappeared. How can i solve this problem.
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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/test" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="66dp"
android:text="Click here to Rotate" />
</RelativeLayout>
ImageResizeTestActivity.java
public class ImageResizeTestActivity extends Activity {
/** Called when the activity is first created. */
Button click;
ImageView img;
static File rotated_File;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
click = (Button) findViewById(R.id.button1);
img = (ImageView) findViewById(R.id.imageView1);
String fname = "Rotated_Image.jpg";
rotated_File = new File("/sdcard/" + fname);
click.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (!(rotated_File.exists())) {
Log.v("Inside if", "if");
rotateImage();
} else {
Log.v("Inside else", "else");
rotateImage(rotated_File.getAbsolutePath());
}
}
});
}
protected void rotateImage(String absolutePath) {
// TODO Auto-generated method stub
Bitmap myImg = BitmapFactory.decodeFile(absolutePath);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(),
myImg.getHeight(), matrix, true);
saveImage_Rotate(rotated);
img.setImageBitmap(rotated);
}
protected void rotateImage() {
// TODO Auto-generated method stub
Bitmap myImg = BitmapFactory.decodeResource(getResources(),
R.drawable.test);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(),
myImg.getHeight(), matrix, true);
saveImage_Rotate(rotated);
img.setImageBitmap(rotated);
}
static void saveImage_Rotate(Bitmap dest2) {
if (rotated_File.exists())
rotated_File.delete();
try {
FileOutputStream out = new FileOutputStream(rotated_File);
dest2.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
after rotating

A quick look on the problem. You save the jpg several times, and during the (lossy)compression it will degrade more and more.
I'd suggest you use png instead

Related

Android Wallpaper App - Resizing Images for scrollable background

I have a wallpaper app, which sets a selected image as background for the phone's menu. It is scrollable (by default), but the problem is that the background is just a cutout of the original image. Here is my code to set the image as background:
private Bitmap image = [...];
[...]
private void setBackgroundImage(){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(pic);
} catch (IOException e) {
e.printStackTrace();
}
}
My question now is: How can I determine the right size for the image, so that every phone has the entire picture as it's background picture and not just a cutout?
my java file: like this
public class MainActivity extends AppCompatActivity {
Button button;
ImageView imageView;
WallpaperManager wallpaperManager ;
Bitmap bitmap1, bitmap2 ;
DisplayMetrics displayMetrics ;
int width, height;
BitmapDrawable bitmapDrawable ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
imageView = (ImageView)findViewById(R.id.imageView);
wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
bitmap1 = bitmapDrawable.getBitmap();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetScreenWidthHeight();
SetBitmapSize();
wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
try {
wallpaperManager.setBitmap(bitmap2);
wallpaperManager.suggestDesiredDimensions(width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void GetScreenWidthHeight(){
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
Toast.makeText(MainActivity.this,"width:"+width+", height:"+height,Toast.LENGTH_SHORT).show();
}
public void SetBitmapSize(){
bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);
}
}
and my layout file. like this:
<?xml version="1.0" encoding="utf-8"?>
<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">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:src="#drawable/sample_image_wallpaper"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click here to Set this image as Wallpaper in android programmatically"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="94dp" />
</RelativeLayout>
Hope this will help.

Android Matrix postRotate and postTranslate applied to a Bitmap

Here is a code snippet which I wrote trying to understand Matrix (postRotate and postTranslate to be more exact).
Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mImageView2;
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.btn:
Matrix matrix = new Matrix();
matrix.postRotate(90);
matrix.postTranslate(200, 0);
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, null);
Bitmap bitmap2 = Bitmap.createBitmap(
bitmap,
0,
0,
bitmap.getWidth(),
bitmap.getHeight(),
matrix,
true
);
mImageView2.setImageBitmap(bitmap2);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(this);
mImageView2 = (ImageView) findViewById(R.id.image2);
}
}
XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="sample2.com.sample_app.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ImageView
android:id="#+id/image2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ccc"
android:scaleType="matrix"
tools:src="#mipmap/ic_launcher" />
</LinearLayout>
The problem is that the bitmap is rotated but not moved anywhere:
What am I doing wrong?

Resize image to fit ImageButton

I'm really new at this and I'm trying to load profile pics from gallery and camera into ImageButton. I'm able to add image from gallery but the image does not fit completely into the ImageButton. Some space still gets left out from the imagebutton. I want the image to automatically fit into imagebutton.
<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.sam.sport.MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/LL1" >
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<ImageButton
android:id="#+id/profile_pic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_launcher"
android:scaleType="fitXY"
android:adjustViewBounds="true" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Activity class is as below:-
public class MainActivity extends Activity {
ImageButton ib;
private static Bitmap Image = null;
private static final int GALLERY = 1;
private static Bitmap rotateImage = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib = (ImageButton)findViewById(R.id.profile_pic);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ib.setImageBitmap(null);
if (Image != null)
Image.recycle();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode != 0) {
Uri mImageUri = data.getData();
try {
Image = Media.getBitmap(this.getContentResolver(), mImageUri);
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,
true);
ib.setImageBitmap(rotateImage);
} else
ib.setImageBitmap(Image);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
}
Convert it to Drawable then use setBackgroundDrawable insted of setImageBitmap
Drawable drawable = new BitmapDrawable(rotateImage);
ib.setBackgroundDrawable(drawable);
Use below line of code for re-sizing your bitmap
Bitmap BITMAP_IMAGE = Bitmap.createBitmap(IMAGE_VIEW.getWidth(),IMAGE_VIEW.getHeight(), Bitmap.Config.RGB_565);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(BITMAP_IMAGE, 100, 100, false); ////Here BITMAP_IMAGE is your bitmap which you want to resize
Get the imageButton height and width
Bitmap bitmapScaled = Bitmap.createScaledBitmap(Image, ib_width, ib_height, true);
Drawable drawable = new BitmapDrawable(bitmapScaled);
ib.setBackgroundDrawable(drawable);
Keep in mind about OOM exception.
To get imageButton height and width look into this and this
I've got the perfect solution. To resize imageview I used the below code as provided in the [Android ImageView adjusting parent's height and fitting width
public class ResizableImageView extends ImageView {
public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
Drawable d = getDrawable();
if(d!=null){
// ceil not round - avoid thin vertical gaps along the left/right edges
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
setMeasuredDimension(width, height);
}else{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
]1

NetworkImageView not loading the image from the first time

I'm trying to upload an Image from my API to show it as profile picture, the problem is from the first time that the user opens the navdrawer the image doesn't load and it makes the entire layout disappear, but from the second time it all works, and I notice that it happens when the width of the image is less than the height. This is the class that I'm using:
public class CircledNetworkImageView extends ImageView {
public boolean mCircled;
/**
* The URL of the network image to load
*/
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/**
* Local copy of the ImageLoader.
*/
private ImageLoader mImageLoader;
/**
* Current ImageContainer. (either in-flight or finished)
*/
private ImageLoader.ImageContainer mImageContainer;
public CircledNetworkImageView(Context context) {
this(context, null);
}
public CircledNetworkImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircledNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets URL of the image that should be loaded into this view. Note that calling this will
* immediately either set the cached image (if available) or the default image specified by
* {#link CircledNetworkImageView#setDefaultImageResId(int)} on the view.
* <p/>
* NOTE: If applicable, {#link CircledNetworkImageView#setDefaultImageResId(int)} and
* {#link CircledNetworkImageView#setErrorImageResId(int)} should be called prior to calling
* this function.
*
* #param url The URL that should be loaded into this ImageView.
* #param imageLoader ImageLoader that will be used to make the request.
*/
public void setImageUrl(String url, ImageLoader imageLoader) {
mUrl = url;
mImageLoader = imageLoader;
// The URL has potentially changed. See if we need to load it.
loadImageIfNecessary(false);
}
/**
* Sets the default image resource ID to be used for this view until the attempt to load it
* completes.
*/
public void setDefaultImageResId(int defaultImage) {
mDefaultImageId = defaultImage;
}
/**
* Sets the error image resource ID to be used for this view in the event that the image
* requested fails to load.
*/
public void setErrorImageResId(int errorImage) {
mErrorImageId = errorImage;
}
/**
* Loads the image for the view if it isn't already loaded.
*
* #param isInLayoutPass True if this was invoked from a layout pass, false otherwise.
*/
void loadImageIfNecessary(final boolean isInLayoutPass) {
int width = getWidth();
int height = getHeight();
ScaleType scaleType = getScaleType();
boolean wrapWidth = false, wrapHeight = false;
if (getLayoutParams() != null) {
wrapWidth = getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT;
wrapHeight = getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT;
}
// if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content
// view, hold off on loading the image.
boolean isFullyWrapContent = wrapWidth && wrapHeight;
if (width == 0 && height == 0 && !isFullyWrapContent) {
return;
}
// if the URL to be loaded in this view is empty, cancel any old requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
int maxWidth = wrapWidth ? 0 : width;
int maxHeight = wrapHeight ? 0 : height;
// The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageLoader.ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
}
#Override
public void onResponse(final ImageLoader.ImageContainer response, boolean isImmediate) {
// If this was an immediate response that was delivered inside of a layout
// pass do not set the image immediately as it will trigger a requestLayout
// inside of a layout. Instead, defer setting the image by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
#Override
public void run() {
onResponse(response, false);
}
});
return;
}
if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
}
}, maxWidth, maxHeight, scaleType);
// update the ImageContainer to be the new bitmap container.
mImageContainer = newContainer;
}
private void setDefaultImageOrNull() {
if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
} else {
setImageBitmap(null);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
loadImageIfNecessary(true);
}
#Override
protected void onDetachedFromWindow() {
if (mImageContainer != null) {
// If the view was bound to an image request, cancel it and clear
// out the image from the view.
mImageContainer.cancelRequest();
setImageBitmap(null);
// also clear out the container so we can reload the image if necessary.
mImageContainer = null;
}
super.onDetachedFromWindow();
}
#Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageBitmap(Bitmap bm) {
mCircled = false;
super.setImageBitmap(bm);
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageResource(int resId) {
mCircled = false;
super.setImageResource(resId);
}
/**
* In case the bitmap is manually changed, we make sure to
* circle it on the next onDraw
*/
#Override
public void setImageDrawable(Drawable drawable) {
mCircled = false;
super.setImageDrawable(drawable);
}
/**
* We want to make sure that the ImageView has the same height and width
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int diw = drawable.getIntrinsicWidth();
if (diw > 0) {
int height = width * drawable.getIntrinsicHeight() / diw;
setMeasuredDimension(width, height);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onDraw(Canvas canvas) {
//Let's circle the image
if (!mCircled && getDrawable() != null) {
Drawable d = getDrawable();
try {
//We use reflection here in case that the drawable isn't a
//BitmapDrawable but it contains a public getBitmap method.
Bitmap bitmap = (Bitmap) d.getClass().getMethod("getBitmap").invoke(d);
if (bitmap != null) {
Bitmap circleBitmap = getCircleBitmap(bitmap);
setImageBitmap(circleBitmap);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
//Seems like the current drawable is not a BitmapDrawable or
//that is doesn't have a public getBitmap() method.
}
//Mark as circled even if it failed, because if it fails once,
//It will fail again.
mCircled = true;
}
super.onDraw(canvas);
}
/**
* Method used to circle a bitmap.
*
* #param bitmap The bitmap to circle
* #return The circled bitmap
*/
public static Bitmap getCircleBitmap(Bitmap bitmap) {
int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
Bitmap output = Bitmap.createBitmap(size,
size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
paint.setAlpha(254);
RectF rect = new RectF(0, 0, size, size);
int radius = size / 2;
canvas.drawRoundRect(rect, radius, radius, paint);
return output;
}
}
I came up with that solution, but I didn't like it, because the image loses its quality:
public class UserActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_user);
camera = (ImageView) findViewById(R.id.camera);
fechar = (TextView) findViewById(R.id.fechar);
editar = (TextView) findViewById(R.id.editar);
membro = (TextView) findViewById(R.id.membro);
nome = (TextView) findViewById(R.id.nome_usuario);
email = (TextView) findViewById(R.id.email_usuario);
email = (TextView) findViewById(R.id.email_usuario);
profilePic = (NetworkImageView) findViewById(R.id.foto);
mImageView = (ImageView) findViewById(R.id.cropped);
progress_wheel = (ProgressWheel) findViewById(R.id.progress_wheel);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(UserActivity.this);
getImageFrom.setTitle("Abrir com:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else if (which == 1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
dialog.dismiss();
}
});
getImageFrom.show();
}
});
profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
profilePic.setDefaultImageResId(R.drawable.avatar_);
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
profilePic.setVisibility(View.GONE);
progress_wheel.setVisibility(View.VISIBLE);
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
Log.i("Image File Path", "" + selectedImagePath);
mImageCaptureUri = Uri.parse(selectedImagePath);
final BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = 8;
Bitmap photo = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), option);
photo = Bitmap.createScaledBitmap(photo, 200, 200, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
previewCapturedImage(f.getAbsolutePath());
profilePic.setVisibility(View.VISIBLE);
progress_wheel.setVisibility(View.GONE);
profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));
break;
case PICK_FROM_FILE:
profilePic.setVisibility(View.GONE);
progress_wheel.setVisibility(View.VISIBLE);
mImageCaptureUri = data.getData();
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
Log.i("Image File Path", "" + selectedImagePath);
mImageCaptureUri = Uri.parse(selectedImagePath);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap photoGaleria = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), options);
photoGaleria = Bitmap.createScaledBitmap(photoGaleria, 200, 200, false);
ByteArrayOutputStream bytesG = new ByteArrayOutputStream();
photoGaleria.compress(Bitmap.CompressFormat.JPEG, 100, bytesG);
File fG = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
fG.createNewFile();
FileOutputStream foG = new FileOutputStream(fG);
foG.write(bytesG.toByteArray());
foG.close();
previewCapturedImage(fG.getAbsolutePath());
profilePic.setVisibility(View.VISIBLE);
progress_wheel.setVisibility(View.GONE);
profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));
break;
}
} catch (Exception e)
{
e.printStackTrace();
}
}
private void previewCapturedImage(String path) {
try {
UploadFoto mUpload = new UploadFoto(path);
mUpload.setEventoListener(new IExecutarTarefa<UploadFoto>() {
#Override
public void AntesDeExecutar(UploadFoto tarefa) {
}
#Override
public void DepoisDeExecutar(UploadFoto tarefa) {
if (tarefa.getResposta()[0].equals("200")) {
GlobalModel.getPerfil().setIdDaImagem(WebService.imgURL + tarefa.getResposta()[1].replace("\"", ""));
profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
}
}
});
mUpload.execute();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
}
#Override
protected void onResume() {
super.onResume();
CarregarPerfil mCarrega = new CarregarPerfil();
mCarrega.execute();
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:wheel="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<include
android:id="#+id/toolbar_user"
layout="#layout/toolbaruser" />
<RelativeLayout
android:id="#+id/campoImagem"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="#+id/toolbar_user"
android:background="#color/armadillo">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/foto"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/user"
android:visibility="visible" />
<com.pnikosis.materialishprogress.ProgressWheel
android:id="#+id/progress_wheel"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:visibility="gone"
wheel:matProg_barColor="#color/white"
wheel:matProg_progressIndeterminate="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/cropped"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:visibility="visible"/>
<ImageView
android:id="#+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:padding="15dp"
android:src="#drawable/ic_camera" />
<TextView
android:id="#+id/Button_crop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center"
android:padding="15dp"
android:text="Salvar"
android:textColor="#color/white"
android:visibility="gone" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/membro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="Membro Retornar desde Julho de 2015"
android:textColor="#color/star_dust" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/campoImagem"
android:layout_marginBottom="30dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:text="Nome"
android:textColor="#color/star_dust"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/nome_usuario"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:textColor="#color/armadillo"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/entrar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="E-mail"
android:textColor="#color/star_dust"
android:textSize="#dimen/text1" />
<TextView
android:id="#+id/email_usuario"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="0dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:text="jgvidotto#gmail.com"
android:textColor="#color/armadillo"
android:textSize="#dimen/text1" />
</LinearLayout>
</RelativeLayout>
Because you have not posted your Activity calling the Navigation Drawer, so I have used both your CircledNetworkImageView class and built-in NetworkImageView in my project. It works well. Please refer to the following:
CustomNavigationDrawer.java:
public class CustomNavigationDrawer {
private static ActionBarDrawerToggle sDrawerToggle;
public static DrawerLayout setUpDrawer(final Context context) {
final Activity activity = ((Activity) context);
DrawerLayout sDrawerLayout = (DrawerLayout) activity.findViewById(R.id.drawer_layout);
if (activity.getActionBar() != null) {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
activity.getActionBar().setHomeButtonEnabled(true);
}
sDrawerToggle = new ActionBarDrawerToggle(
activity,
sDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
activity.invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View drawerView) {
activity.invalidateOptionsMenu();
syncState();
}
};
sDrawerLayout.setDrawerListener(sDrawerToggle);
return sDrawerLayout;
}
public static void syncState() {
sDrawerToggle.syncState();
}
public static void onConfigurationChanged(Configuration newConfig) {
sDrawerToggle.onConfigurationChanged(newConfig);
}
}
MainActivity.java:
public class MainActivity extends Activity {
final Context mContext = this;
final String mUrl = "http://.../getimage";
NetworkImageView mNetworkImageView;
CircledNetworkImageView mCircledNetworkImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomNavigationDrawer.setUpDrawer(this);
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
mNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
mCircledNetworkImageView = (CircledNetworkImageView) findViewById(R.id.circleImageView);
mCircledNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
CustomNavigationDrawer.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
CustomNavigationDrawer.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
activity_main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/networkImageView"
android:layout_width="300dp"
android:layout_height="wrap_content" />
<com.example.networkimageview.CircledNetworkImageView
android:id="#+id/circleImageView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/networkImageView" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
You can create a new sample project and use my sample code. Hope this helps!
if (width == 0 && height == 0 && !isFullyWrapContent) {
I guess the first you loadImage code will return because of this condition. The width and height is equal to 0 before the whole UI load success. log before this condition return. Hope this can help you.

how to set contentview declaratively or use customview class

i'd like to load a picture from sdcard into my view then draw upon it. so far i can take the picture and display it in an imageview after i've drawn a circle on the bitmap but this is not how it should be done. I think that i need to create a custom view class and override it's onDraw(). Atm i have a relative layout with a surfaceview, after the surfaceview i have the imageview and buttons. My question is if i write a custom view class to handle the drawing, i would then pass that to my activity's setContent view, what is confusing me is if the layout is declared declaratively via the xml file, how can i set the activity's setContentView() to the custom view class that handles the drawing?
thanks mat
[edit]
here's the xml layout i'm using. this is not how i should do it using an imageview.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content" android:gravity="fill">
<ImageView android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></ImageView>
<com.tecmark.HorizontalSlider android:id="#+id/slider"
android:indeterminateOnly="false"
android:progressDrawable="#android:drawable/progress_horizontal"
android:indeterminateDrawable="#android:drawable/progress_indeterminate_horizontal"
android:minHeight="20dip"
android:maxHeight="20dip" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class LoadPic extends Activity{
private static final String TAG = "Loadpic";
private ImageView imageview;
private File tempFile;
private byte[] imageArray;
private HorizontalSlider slider;
private Canvas canvas;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.e(TAG, " loadpic onCreate");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.load2);
setProgressBarVisibility(true);
slider = (HorizontalSlider) this.findViewById(R.id.slider);
slider.setOnProgressChangeListener(changeListener);
imageview = (ImageView)findViewById(R.id.imageView1);
tempFile = new File(Environment.getExternalStorageDirectory().
getAbsolutePath() + "/"+"image.jpg");
imageArray = new byte[(int)tempFile.length()];
try{
InputStream is = new FileInputStream(tempFile);
BufferedInputStream bis = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bis);
int i = 0;
while (dis.available() > 0) {
imageArray[i] = dis.readByte();
i++;
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 5;
Bitmap bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
Log.e(TAG, bm.toString());
//imageview.setImageBitmap(bm);
Bitmap bmOverlay = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
canvas = new Canvas(bmOverlay);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.STROKE);
canvas.drawBitmap(bm, new Matrix(), null);
canvas.drawCircle(50, 50, 25, paint);
imageview.setImageBitmap(bmOverlay);
}// end of onCreate
private OnProgressChangeListener changeListener = new OnProgressChangeListener() {
#Override
public void onProgressChanged(View v, int progress) {
// TODO Auto-generated method stub
setProgress(progress);
}
};
}//end of Activity
What i'm thinking of doing is creating a customview class that handles the drawing on the bitmap. But if i do this then how do i make setContentView() to point to my customView class when it point to the xml file. Sorry if i missing something here.
If you want to have a custom view for the bitmap and drawing then you can simply extend ImageView and override the paint method. Something like that:
public class MyImage extends ImageView {
...
#Override
public void paint(...){}
}
And in the xml layout change the ImageView to
<what.ever.package.MyImage ... />

Categories

Resources