Android bitmap/thumbnail scaling - android

I am generating a image-view based on the size of the screen I am working on. I am attempting to put a place holder for a thumbnail image. After the user takes a picture it is placed within this place holder and scaled to fit. I am unsure if this is the correct way to scale a thumbnail image. Has anyone done something similar?
CameraActivity:
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraActivity extends AppCompatActivity {
private static final String TAG = "CameraActivty";
static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView mImageThumb;
private Button cameraButton;
private EditText note;
private RelativeLayout layout;
private String mCurrentPhotoPath;
private File photoFile;
private int targetW;
private int targetH;
InputMethodManager in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#000000"));
getSupportActionBar().setBackgroundDrawable(colorDrawable);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
layout = (RelativeLayout) findViewById(R.id.cameraRelLayout);
mImageThumb = (ImageView) findViewById(R.id.imageThumb);
getScreenSize();
mImageThumb.getLayoutParams().height = targetH;
mImageThumb.getLayoutParams().width = targetW;
cameraButton = (Button) findViewById(R.id.pictureButton);
note = (EditText) findViewById(R.id.note);
note.setScroller(new Scroller(this));
note.setMaxLines(1);
note.setVerticalScrollBarEnabled(true);
note.setMovementMethod(new ScrollingMovementMethod());
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
hideKeyboard(view);
return false;
}
});
note.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
showKeyboard(view);
return false;
}
});
}
private void getScreenSize(){
DisplayMetrics display = this.getResources().getDisplayMetrics();
int screenWidth = display.widthPixels;
targetW = screenWidth - (screenWidth / 8);
targetH = (targetW * 3) / 4;
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
setPic();
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private void setPic() {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
mImageThumb.setImageBitmap(rotateBitmap(bmOptions));
}
public Bitmap rotateBitmap(BitmapFactory.Options ops){
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, ops);
Bitmap scaledMap = Bitmap.createScaledBitmap(bitmap, targetW, targetH, true);
Bitmap rotatedMap = Bitmap.createBitmap(scaledMap, 0, 0, scaledMap.getWidth(), scaledMap.getHeight(), matrix, true);
return rotatedMap;
}
public void hideKeyboard(View view) {
in.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
public void showKeyboard(View view) {
in.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
#Override
protected void onResume() {
super.onResume();
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
CameraXML
<?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="match_parent"
android:focusableInTouchMode="true"
android:id="#+id/cameraRelLayout">
<ImageView
android:layout_marginTop="25dp"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="#drawable/image_holder"
android:layout_centerHorizontal="true"
android:id="#+id/imageThumb"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:layout_alignParentBottom="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:enabled="true"
android:minLines="2"
android:textIsSelectable="true"
android:focusable="true"
android:isScrollContainer="true"
android:layout_weight="1"
android:gravity="top"
android:padding="10dp"
android:ems="10"
android:hint="Problem Description"
android:layout_marginBottom="15dp"
android:id="#+id/note"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Picture"
android:id="#+id/pictureButton"
android:background="#drawable/default_button"
android:layout_gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="8dp" />
</LinearLayout>
</RelativeLayout>

Related

PinchToZoom not working with multiple activities in Android

I am trying to implement pinch to zoom, in my project i have used multiple activities which interconnect them. Initially when i had my complete project in one activity it was performing zoom, however it is not the case with multiple activities.
CODE: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kmay.calculatephase">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:debuggable="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoadImage" >
</activity>
<activity android:name=".Phase" >
</activity>
<activity android:name=".ColorGray" >
</activity>
<activity android:name=".Information" >
</activity>
</application>
CODE: MainActivity.java
package com.example.stiwari.myappli;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button btn1;Bitmap imgb;Bitmap operation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
Bitmap bmp;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rawIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
rawIntent.setDataAndType(data, "image/*");
startActivityForResult(rawIntent, 10);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
if(requestCode==10){
final float red = (float) 0.299;
final float green = (float) 0.587;
final float blue = (float) 0.114;
final Uri imagef = data.getData();
InputStream streamI;
try {
streamI = getContentResolver().openInputStream(imagef);
//Create bitmap from selected image
imgb = BitmapFactory.decodeStream(streamI);
//Define rows and columns of selected image
int rows = imgb.getHeight();int cols = imgb.getWidth();
operation = Bitmap.createBitmap(cols, rows, imgb.getConfig());
//Convert original image to Gray Image
for (int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
int p = imgb.getPixel(i,j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
r = (int) (red*r);
g = (int) (green*g);
b = (int) (blue*b);
int gray = (int) (r*0.299+g*0.587+b*0.114);
operation.setPixel(i, j, Color.argb(Color.alpha(p), gray, gray, gray));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();}
}
//Use Intent property to send data to Main2Activity.class
Intent i = new Intent(this,Main2Activity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
operation.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
}
}
CODE: activity_main.xml
<?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" 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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Page"
android:id="#+id/btn1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
CODE:Main2Activity.java
package com.example.stiwari.myappli;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class Main2Activity extends AppCompatActivity {
Bitmap imgb;
ImageView imageView1;float scaleFactor;View view;
ScaleGestureDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView1 = (ImageView) findViewById(R.id.imageView1);
detector = new ScaleGestureDetector(this, new ScaleListener());
if (getIntent().hasExtra("byteArray")) {
//ImageView previewThumbnail = new ImageView(this);
imgb = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
//previewThumbnail.setImageBitmap(imgb);
}imageView1.setImageBitmap(imgb);
imageView1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Main2Activity.this.view = v;
detector.onTouchEvent(event);
return false;
}
});
}
CODE: activity_main2.xml
<?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" 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="com.example.stiwari.myappli.Main2Activity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Use the below code for Pinch Zoom.
ScaleGestureDetector detector = new ScaleGestureDetector(this, new ScaleListener());
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = (scaleFactor < 1 ? 1 : scaleFactor);
scaleFactor = ((float) ((int) (scaleFactor * 100))) / 100;
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
return true;
}
}
Also,Setup a touchListener to you view on onCreate(The one which you want to zoom).
example
(YOUR_VIEW).setClickable(true);
(YOUR_VIEW).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
MainActivity.this.view = v;
detector.onTouchEvent(event);
return false;
});
Hope this will help :)
UPDATE 1:
Based on your code.change condition like this
imageView1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
} else {
Main2Activity.this.view = v;
detector.onTouchEvent(event);
}
return false;
}
});

Add Edit-Text dynamically on Horizontal List View item

I am developing a photo editor app. Where I am giving an option of add text to image i.e writing some CAPTION or you can say TAG on that image. What I want is on "A"`s click, an Edit-Text should be added to the in image. Where can I insert name or any text.
What I want is describes in below image...
My code 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.R.string;
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, HListViewColor;
/* 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);
HListViewColor = (HorizontalListView) findViewById(R.id.horizontal_list_view_color);
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;
case 1:
/* Space for adding dynamic Edit-Text */
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.java
<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>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_color"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
I want similar to below image...
Thanks in advance.

TouchImageView zoom issue

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.

How to make ImageButton a circle and to fit Uploaded Image inside that circle?

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

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..

Categories

Resources