am developing a face recognition app. it gets the first bitman on a previous activity but it generates a new one with the faces labeled and i'd like to save that new bitmap. i've lost one day or two figuring it out but none of the answers i've tried helps.
this is the code for this activity, its supposed to save the bitmap into gallery when saveButton is pressed.
public class FaceRecognizeActivity extends AppCompatActivity {
Bitmap bmp, carasReconocidas;
ImageView imagen;
int contador;
Button guardarRostro, copiarRegistroRostro;
TextView descripcion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setStatusBarColor(this.getResources().getColor(R.color.colorAccentLight));
setContentView(R.layout.activity_reconocer_rostros);
guardarRostro = (Button) findViewById(R.id.guardarRostros);
copiarRegistroRostro = (Button) findViewById(R.id.copiarRostros);
descripcion = (TextView) findViewById(R.id.descripcionRostros);
byte[] byteArray = getIntent().getByteArrayExtra("image");
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
this.imagen = (ImageView) this.findViewById(R.id.caraReconocida);
imagen.setImageBitmap(bmp);
contador = 0;
final Paint boxPaint = new Paint();
carasReconocidas = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas (carasReconocidas);
canvas.drawBitmap(bmp, 0,0,null);
boxPaint.setStrokeWidth(8);
boxPaint.setColor(Color.GREEN);
boxPaint.setStyle(Paint.Style.STROKE);
procesar( canvas, boxPaint);
descripcion.setText(cantidad());
guardarRostro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO
}
})
;
copiarRegistroRostro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Registro de rostros ", descripcion.getText().toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "copiado", Toast.LENGTH_SHORT).show();
}
})
;
}
public void procesar(Canvas canvas, Paint boxPaint){
FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext())
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.build();
if (!faceDetector.isOperational()){
Toast.makeText(getApplicationContext(), "Algo saliĆ³ mal", Toast.LENGTH_SHORT).show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bmp).build();
SparseArray<Face> sparseArray = faceDetector.detect(frame);
for (int i = 0 ; i < sparseArray.size(); i++){
Face face = sparseArray.valueAt(i);
float x1= face.getPosition().x;
float y1= face.getPosition().y;
float x2= x1 + face.getWidth();
float y2= y1 + face.getHeight();
RectF rectF = new RectF(x1,y1,x2,y2);
canvas.drawRoundRect(rectF,2,2, boxPaint);
contador=contador + 1;
}
imagen.setImageBitmap(carasReconocidas);
}
public String cantidad(){
String texto;
if (contador == 0){
texto= "Parece que no hay personas en esta imagen.";
} else if (contador == 1) {
texto="Se reconociĆ³ una persona";
}else {
texto="Se reconocieron " + Integer.toString(contador) + " personas.";
}
return texto;
}
#Override
public void onBackPressed() {
Intent anotherIntent = new Intent(FaceRecognizeActivity.this, MenuActivity.class);
startActivity(anotherIntent);
}
}
Related
I'm having problems in the following context, I need to make signatures on a form that is an image in PNG or JPG, this functionality belongs to a mobile application with Android system.
The status is in the following situation, I can place the signature in the place where the user clicked. But I'm having trouble resizing the signature bitmap proportionally to the amount of zoom that was given. You need to position the signature Bitmap at the point the user clicked on, but referring to the image and not the screen.
I have browsed a lot of topics on the internet, many here in StackOverflow, but I do not find any that gives me any idea how I can do such an activity. I have already arrived several times on the third page of Google.
Can anyone help me, or can you give me some insight into how I can do this?
problem sketch
My code
public class SignatureActivity extends Activity implements OnClickListener {
private LinearLayout mContent;
private Button mClear, mSave, mCancel;
private View view;
private Dialog dialog;
private Signature mSignature;
private TouchImageView img;
private float xPosition;
private float yPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_signature);
img = (TouchImageView) findViewById(R.id.iv_form);
img.setImageResource(R.drawable.imp_009_tiss_1200x859);
img.setOnClickListener(this);
// Dialog Function
dialog = new Dialog(SignatureActivity.this);
// Removing the features of Normal Dialogs
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_signature);
dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mSignature = (Signature) dialog.getWindow().findViewById(R.id.signatureView1);
dialog.setCancelable(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_form:
dialog_action();
break;
default:
break;
}
}
public void carregaComponentes() {
mContent = (LinearLayout) dialog.findViewById(R.id.ll_area_assinatura);
mClear = (Button) dialog.findViewById(R.id.clear);
mSave = (Button) dialog.findViewById(R.id.save);
mCancel = (Button) dialog.findViewById(R.id.cancel);
mSignature = (Signature) dialog.findViewById(R.id.signatureView1);
}
public void dialog_action() {
carregaComponentes();
mSignature.setBackgroundColor(Color.WHITE);
mSignature.setSigColor(255, 0, 0, 255);
view = mContent;
mClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clearSignature();
}
});
mSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
view.setDrawingCacheEnabled(true);
if (saveSignature(view)) {
dialog.dismiss();
} else {
mSignature.clearSignature();
}
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
dialog.dismiss();
mSignature.clearSignature();
}
});
dialog.show();
}
public boolean saveSignature(View view) {
DisplayMetrics dm = new DisplayMetrics();
float dpi = dm.scaledDensity;
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenW = dm.widthPixels;
int screenH = dm.heightPixels;
Bitmap assinatura = mSignature.getImage();
Bitmap assinaturaRedimensionada = Bitmap.createScaledBitmap(
assinatura,
(Integer.valueOf((int) (screenW * 0.20))),
(Integer.valueOf((int) (screenH * 0.070))),
false);
img.buildDrawingCache();
Bitmap imgGto = img.getDrawingCache();
Bitmap gtoAssinada = Bitmap.createBitmap(imgGto.getWidth(), imgGto.getHeight(), imgGto.getConfig());
Canvas canvas = new Canvas(gtoAssinada);
canvas.drawBitmap(imgGto, new Matrix(), null);
canvas.drawBitmap(assinaturaRedimensionada, TouchImageViewListener.x, TouchImageViewListener.y, null);
// Creating Separate Directory for saving Generated Images
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = "GTO_assinada" + pic_name + ".png";
File fichero = new File(sd, StoredPath);
try {
if (sd.canWrite()) {
fichero.createNewFile();
OutputStream os = new FileOutputStream(fichero);
gtoAssinada.compress(Bitmap.CompressFormat.PNG, 90, os);
os.close();
img.setImageBitmap(gtoAssinada);
mSignature.clearSignature();
Toast.makeText(getApplicationContext(), "GTO Assinada com Sucesso!", Toast.LENGTH_LONG).show();
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
So we're trying to implement an upload image feature in our Android App.
In our registration page, there is an upload button and once pressed, it should redirect to the image gallery and once an image is selected, it should be displayed in the ImageView placed.
Here's an excerpt of the code we're trying to work on.
The issue is, for some images it is correctly displayed but for some, it is either rotated 90 degrees to the right or 180 degrees.
What could be the issue?
public class Register extends AppCompatActivity {
private String mName = "";
private String mUsername = "";
private String mPassword = "";
private String mCompany = "";
private String mContact = "";
private static final int PICK_IMAGE = 100;
ImageView imageView;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Intent recvdIntent = getIntent();
mName = recvdIntent.getStringExtra("NAME");
mUsername = recvdIntent.getStringExtra("USERNAME");
mPassword = recvdIntent.getStringExtra("PASSWORD");
mCompany = recvdIntent.getStringExtra("COMPANY");
mContact = recvdIntent.getStringExtra("CONTACT");
imageView = (ImageView)findViewById(R.id.imageView);
Button btnSubmit = (Button) findViewById(R.id.btn_register);
btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
submitUserData();
Intent launchIntent = new Intent(Register.this, Category.class);
return;
}
}
);
Button upload = (Button) findViewById(R.id.btn_upload);
upload.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
return;
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
private void submitUserData() {
EditText edtName = (EditText) findViewById(R.id.edt_name);
EditText edtCompany = (EditText) findViewById(R.id.edt_company);
EditText edtContact = (EditText) findViewById(R.id.edt_contact);
EditText edtUsername = (EditText) findViewById(R.id.edt_username);
EditText edtPassword = (EditText) findViewById(R.id.edt_password);
TaraApp2 app = (TaraApp2) getApplication();
app.saveUserData(edtName.getText().toString(),edtUsername.getText().toString(),
edtPassword.getText().toString(),
edtCompany.getText().toString(),
edtContact.getText().toString() );
finish();
return;
}
}
Uri selectedImageUri = data.getData();
Bitmap bitmap = scaleImage(this,selectedImageUri);
public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
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);
}
for getting url of the image use this
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
For accessing picture from your gallery you can use the croperino library.
https://android-arsenal.com/details/1/4374
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Croperino.prepareGallery(MainActivity.this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CroperinoConfig.REQUEST_PICK_FILE:
if (resultCode == Activity.RESULT_OK) {
CroperinoFileUtil.newGalleryFile(data, MainActivity.this);
Croperino.runCropImage(CroperinoFileUtil.getmFileTemp(),
MainActivity.this, true, 1, 1, 0, 0);
}
break;
case CroperinoConfig.REQUEST_CROP_PHOTO:
if (resultCode == Activity.RESULT_OK) {
Uri i = Uri.fromFile(CroperinoFileUtil.getmFileTemp());
ivMain.setImageURI(i);
//Do saving / uploading of photo method here.
//The image file can always be retrieved via
CroperinoFileUtil.getmFileTemp()
}
break;
default:
break;
}
}
java code
package"";
import yuku.ambilwarna.AmbilWarnaDialog;
/**
* Created by pc-4 on 5/31/2016.
*/
public class EditWindow extends ActionBarActivity implements View.OnClickListener {
private static final int SELECT_FILE = 1;
ImageView iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12;
Bitmap myBitmap;
ArrayList<Integer> vericalArrayList = new ArrayList<Integer>();
private LinearLayout hv;
int color = 0xffffff00;
LinearLayout linear_popup;
Context context = this;
String name, meaning;
int j = 0;
LinearLayout[] linearlayout;
LinearLayout ll_main;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_window);
FinBtViewIds();
ll_main.setBackgroundResource(R.drawable.page_back_ground);
linear_popup = (LinearLayout) findViewById(R.id.linear_popup);
Bundle bundle = getIntent().getExtras();
name = bundle.getString("name");
meaning = bundle.getString("meaning");
j = name.length();
linearlayout = new LinearLayout[j];
items = meaning.split("\\s+");
verical_linear();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(EditWindow.this, "FAILES TO SET PIC", Toast.LENGTH_SHORT).show();
}
Drawable drawable = (Drawable) new BitmapDrawable(getResources(), bm);
LinearLayout ll_main = (LinearLayout) findViewById(R.id.linear);
ll_main.setBackground(drawable);
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_background:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.VISIBLE);
break;
case R.id.iv_gallery:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
galleryIntent();
break;
case R.id.iv_text:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
openDialog(true);
break;
case R.id.iv_edit_back:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
onBackPressed();
super.onBackPressed();
break;
case R.id.iv_edit_done:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
ll_main.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(ll_main);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
Intent i=new Intent(EditWindow.this,SaveActivity.class);
startActivity(i);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
break;
case R.id.iv_style:
hv.setVisibility(View.GONE);
if (linear_popup.getVisibility() == View.VISIBLE)
linear_popup.setVisibility(View.GONE);
else {
linear_popup.setVisibility(View.VISIBLE);
}
break;
case R.id.tv_horizontal:
hv.setVisibility(View.GONE);
horizontal_linear();
linear_popup.setVisibility(View.GONE);
break;
case R.id.tv_vertical:
hv.setVisibility(View.GONE);
verical_linear();
linear_popup.setVisibility(View.GONE);
break;
}
}
public void verical_linear() {
ll_main.setOrientation(LinearLayout.VERTICAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
int j = name.length();
final LinearLayout[] linearlayout = new LinearLayout[j];
String[] items = meaning.split("\\s+");
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.HORIZONTAL);
TextView tv = new TextView(this);
int text_id;
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}
tv.setId(text_id);
Toast.makeText(EditWindow.this, String.valueOf(text_id), Toast.LENGTH_SHORT).show();
vericalArrayList.add(text_id);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
t2.setGravity(Gravity.END | Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(2);
t2.setTextSize(20);
t2.setTypeface(face);
t2.setText(items[i]);
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void horizontal_linear() {
ll_main.setOrientation(LinearLayout.HORIZONTAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
int text_id;
tv.setTag(tv.getId());
/*
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}*/
tv.setGravity(Gravity.CENTER);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
/* int text_id2;
Random r1 = new Random();
text_id2 = r1.nextInt();
if (text_id2 < 0) {
text_id2 = text_id2 - (text_id2 * 2);
}*/
t2.setTag(t2.getId());
t2.setGravity(Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(1);
t2.setTypeface(face);
t2.setText(items[i]);
int id=t2.getId();
int id1=tv.getId();
vericalArrayList.add(id);
vericalArrayList.add(id1);
Toast.makeText(EditWindow.this, String.valueOf("1"+id), Toast.LENGTH_SHORT).show();
Toast.makeText(EditWindow.this, String.valueOf("2"+id1), Toast.LENGTH_SHORT).show();
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void FinBtViewIds() {
final ImageView tv_horizontal;
final ImageView tv_vertical;
final ImageView iv_edit_back;
final ImageView iv_done;
final ImageView iv_gallery;
final ImageView iv_background;
final ImageView iv_style;
final ImageView iv_text;
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
iv4=(ImageView)findViewById(R.id.iv4);
iv5=(ImageView)findViewById(R.id.iv5);
iv6=(ImageView)findViewById(R.id.iv6);
iv7=(ImageView)findViewById(R.id.iv7);
iv8=(ImageView)findViewById(R.id.iv8);
iv9=(ImageView)findViewById(R.id.iv9);
iv10=(ImageView)findViewById(R.id.iv10);
iv11=(ImageView)findViewById(R.id.iv11);
iv12=(ImageView)findViewById(R.id.iv12);
ll_main = (LinearLayout) findViewById(R.id.linear);
hv = (LinearLayout) findViewById(R.id.hv);
iv_edit_back = (ImageView) findViewById(R.id.iv_edit_back);
tv_horizontal = (ImageView) findViewById(R.id.tv_horizontal);
tv_vertical = (ImageView) findViewById(R.id.tv_vertical);
iv_done = (ImageView) findViewById(R.id.iv_edit_done);
iv_gallery = (ImageView) findViewById(R.id.iv_gallery);
iv_background = (ImageView) findViewById(R.id.iv_background);
iv_style = (ImageView) findViewById(R.id.iv_style);
iv_text = (ImageView) findViewById(R.id.iv_text);
iv_edit_back.setOnClickListener(this);
iv_done.setOnClickListener(this);
iv_gallery.setOnClickListener(this);
iv_background.setOnClickListener(this);
iv_style.setOnClickListener(this);
iv_text.setOnClickListener(this);
tv_horizontal.setOnClickListener(this);
tv_vertical.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
}
}
void openDialog(boolean supportsAlpha) {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(EditWindow.this, color, supportsAlpha, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
//Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
EditWindow.this.color = color;
displayColor();
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
// Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
void displayColor() {
for (int i = 0; i < vericalArrayList.size(); i++) {
String id = vericalArrayList.get(i).toString();
TextView text = (TextView) findViewById(vericalArrayList.get(i));
text.setTextColor(color);
Toast.makeText(EditWindow.this, id + "/n" + i, Toast.LENGTH_SHORT).show();
}
}
public void Onclick(View v)
{
switch (v.getId())
{
case R.id.iv1:
ll_main.setBackgroundResource(R.drawable.n1);
break;
case R.id.iv2:
ll_main.setBackgroundResource(R.drawable.n2);
break;
case R.id.iv3:
ll_main.setBackgroundResource(R.drawable.n3);
break;
case R.id.iv4:
ll_main.setBackgroundResource(R.drawable.n4);
break;
case R.id.iv5:
ll_main.setBackgroundResource(R.drawable.n5);
break;
case R.id.iv6:
ll_main.setBackgroundResource(R.drawable.n6);
break;
case R.id.iv7:
ll_main.setBackgroundResource(R.drawable.n7);
break;
case R.id.iv8:
ll_main.setBackgroundResource(R.drawable.n8);
break;
case R.id.iv9:
ll_main.setBackgroundResource(R.drawable.n9);
break;
case R.id.iv10:
ll_main.setBackgroundResource(R.drawable.n10);
break;
case R.id.iv11:
ll_main.setBackgroundResource(R.drawable.n11);
break;
case R.id.iv12:
ll_main.setBackgroundResource(R.drawable.n12);
break;
}
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
}
xml
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#color/white"
android:orientation="horizontal"
android:padding="#dimen/value_10"
android:visibility="visible">
</LinearLayout>
i didn't post imports
WHOLE XML DOENOT MATTER HERE SO I JUST here playing with single linearlayout so have added only that
have added full codes
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTextColor(int)' on a null object reference
As you are storing all TextView ids in array list and the only thing you need to do is cast that view to TextView and set text color.
TextView text = (TextView) findViewById(integerArrayList.get(i));
text.setTextColor(Color.RED);
I have an image which a user can paint on in my android application. I decided to add an undo button to it so the user can cancel mistakes. I made it so that when the user draws on the screen, it saves the bitmap to an array. Then when the undo button is pressed, it changes the image to the last bitmap in the array. However, this just keeps setting the image to whatever the current image is (i.e. it doesn't change it at all).
public class edit extends AppCompatActivity implements View.OnClickListener {
float MoveX,MoveY,DownY,DownX,UpY=0,UpX ;
List<Bitmap> undos = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
final ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn2.setOnClickListener(this);
final Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setOnClickListener(this);
final RelativeLayout ViewX = (RelativeLayout) findViewById(R.id.RLXV);
ViewTreeObserver vto = ViewX.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewX.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Intent intent7 = getIntent();
String bitmapXY = (String) intent7.getExtras().get("BitmapImage");
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/" + bitmapXY,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
HttpURLConnection connection = null;
try {
int ViewWidth = ViewX.getMeasuredWidth();
JSONObject photos = response.getJSONObject();
JSONArray linkY = photos.optJSONArray("images");
final JSONObject linkO = linkY.optJSONObject(0);
final String link2 = linkO.optString("source");
URL LINKF = new URL(link2);
connection = (HttpURLConnection) LINKF.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
float HH = (float) bitmap.getHeight();
float WW = (float) bitmap.getWidth();
float ViewWidthX = (float) ViewWidth;
float height = (HH / WW) * ViewWidthX;
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
undos.add(bitmapF);
image1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Display d = getWindowManager().getDefaultDisplay();
float dw = d.getWidth();
float dh = d.getHeight();
float x = event.getX();
float y = event.getY();
float r = 2;
Bitmap BTX = ((BitmapDrawable)image1.getDrawable()).getBitmap();
Canvas canvas = new Canvas(BTX);
canvas.drawBitmap(BTX,0,0,null);
Paint paint1 = new Paint();
int bg1 = buttonchoose.getDrawingCacheBackgroundColor();
ColorDrawable buttonColor = (ColorDrawable) buttonchoose.getBackground();
int bg2 =buttonColor.getColor();
paint1.setColor(bg2);
paint1.setShadowLayer(5, 2, 2, bg2);
paint1.setStrokeWidth(20);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
DownY = event.getY();
DownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
MoveY = event.getY();
MoveX = event.getX();
canvas.drawLine(DownX, DownY, MoveX, MoveY, paint1);
image1.invalidate();
DownX = MoveX;
DownY=MoveY;
break;
case MotionEvent.ACTION_UP:
UpY = event.getY();
UpX = event.getX();
canvas.drawLine(DownX, DownY, UpX, UpY, paint1);
image1.invalidate();
Bitmap BTXYZ = ((BitmapDrawable)image1.getDrawable()).getBitmap();
break;
}
return true;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "images");
request.setParameters(parameters);
request.executeAsync();
}
});
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonchoose:
final ColorPicker cp = new ColorPicker(edit.this, 0, 0, 0);
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button) cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
int selectedColorR = cp.getRed();
int selectedColorG = cp.getGreen();
int selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
int selectedColorRGB = cp.getColor();
Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setText("");
buttonchoose.setBackgroundColor(selectedColorRGB);
cp.dismiss();
}
});
break;
case R.id.imageButton2:
int newImage = undos.size();
Log.e("Lenght of Array",""+newImage);
if(newImage >=1) {
Bitmap newImage2 = undos.get(newImage-2);
ImageView IMGXV = (ImageView) findViewById(R.id.image1);
IMGXV.setImageBitmap(newImage2);
undos.remove(newImage-1);
}
break;
}
}
}
Try this exact code -
case R.id.imageButton2:
if(undos.size() > 0) {
Bitmap newImage2 = undos.remove(undos.size() - 1);
ImageView IMGXV = (ImageView) findViewById(R.id.image1);
IMGXV.setImageBitmap(newImage2);
}
break;
EDIT Added an extra line in onGlobalLayout(), try this -
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
//The extra line before adding bitmap to arraylist.
Bitmap bitmapFcopy = bitmapFcopy.copy(bitmapFcopy.getConfig(), true);
undos.add(bitmapFcopy);
EDIT 2
public class edit extends AppCompatActivity implements View.OnClickListener {
//Declare the imageview here and access this everywhere.
ImageView image1;
float MoveX,MoveY,DownY,DownX,UpY=0,UpX ;
List<Bitmap> undos = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
//Get the reference here
image1 = (ImageView) findViewById(R.id.image1);
final ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn2.setOnClickListener(this);
final Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setOnClickListener(this);
final RelativeLayout ViewX = (RelativeLayout) findViewById(R.id.RLXV);
ViewTreeObserver vto = ViewX.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewX.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Intent intent7 = getIntent();
String bitmapXY = (String) intent7.getExtras().get("BitmapImage");
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/" + bitmapXY,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
HttpURLConnection connection = null;
try {
int ViewWidth = ViewX.getMeasuredWidth();
JSONObject photos = response.getJSONObject();
JSONArray linkY = photos.optJSONArray("images");
final JSONObject linkO = linkY.optJSONObject(0);
final String link2 = linkO.optString("source");
URL LINKF = new URL(link2);
connection = (HttpURLConnection) LINKF.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
float HH = (float) bitmap.getHeight();
float WW = (float) bitmap.getWidth();
float ViewWidthX = (float) ViewWidth;
float height = (HH / WW) * ViewWidthX;
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
//Remove from here and declare this in onCreate() and don't make it final
//final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
undos.add(bitmapF);
image1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Display d = getWindowManager().getDefaultDisplay();
float dw = d.getWidth();
float dh = d.getHeight();
float x = event.getX();
float y = event.getY();
float r = 2;
Bitmap BTX = ((BitmapDrawable)image1.getDrawable()).getBitmap();
Canvas canvas = new Canvas(BTX);
canvas.drawBitmap(BTX,0,0,null);
Paint paint1 = new Paint();
int bg1 = buttonchoose.getDrawingCacheBackgroundColor();
ColorDrawable buttonColor = (ColorDrawable) buttonchoose.getBackground();
int bg2 =buttonColor.getColor();
paint1.setColor(bg2);
paint1.setShadowLayer(5, 2, 2, bg2);
paint1.setStrokeWidth(20);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
DownY = event.getY();
DownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
MoveY = event.getY();
MoveX = event.getX();
canvas.drawLine(DownX, DownY, MoveX, MoveY, paint1);
image1.invalidate();
DownX = MoveX;
DownY=MoveY;
break;
case MotionEvent.ACTION_UP:
UpY = event.getY();
UpX = event.getX();
canvas.drawLine(DownX, DownY, UpX, UpY, paint1);
image1.invalidate();
Bitmap BTXYZ = ((BitmapDrawable)image1.getDrawable()).getBitmap();
break;
}
return true;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "images");
request.setParameters(parameters);
request.executeAsync();
}
});
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonchoose:
final ColorPicker cp = new ColorPicker(edit.this, 0, 0, 0);
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button) cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
int selectedColorR = cp.getRed();
int selectedColorG = cp.getGreen();
int selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
int selectedColorRGB = cp.getColor();
Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setText("");
buttonchoose.setBackgroundColor(selectedColorRGB);
cp.dismiss();
}
});
break;
case R.id.imageButton2:
int newImage = undos.size();
Log.e("Lenght of Array",""+newImage);
if(newImage >=1) {
Bitmap newImage2 = undos.get(newImage-2);
//Don't take reference again here
//ImageView IMGXV = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(newImage2);
undos.remove(newImage-1);
}
break;
}
}
}
I have this class and I want to save my drawing to a jpeg file when the actionbar is clicked.
public class SingleTouchActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventView(this, null));
// Create ActionBar
ActionBar actionBar = getActionBar();
actionBar.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// ActionBar is clicked
switch (item.getItemId()) {
case R.id.sig_reset:
finish();
Intent sigIntent = new Intent(this, SingleTouchActivity.class);
startActivity(sigIntent);
break;
case R.id.sig_save:
//Save to image
break;
}
return true;
}
I searched the web and I found this code snippet:
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.JPEG, 95, new FileOutputStream("/some/location/image.jpg"));
And this one:
//createBitmap(int width, int height, Bitmap.Config config)
// Returns a mutable bitmap with the specified width and height.
Bitmap image = Bitmap.createBitmap(mapRelativeView.getWidth(), mapRelativeView.getHeight(), Bitmap.Config.RGB_565);
//draw(Canvas canvas) -- Manually render this view
//(and all of its children) to the given Canvas.
yourView.draw(new Canvas(image));
//insertImage(ContentResolver cr, Bitmap source, String title, String description)
// Insert an image and create a thumbnail for it.
//uri is the path after the image has been saved.
String uri = Images.Media.insertImage(getContentResolver(), image, "title", null);
The problem is that my SingleTouchActivity set's SingleTouchEventView as content, and I don't know how I have to define my view.
This is Free Hand Draw Example where you can draw anything and save as image in SD Card.
DownLoad Full Source Form Here
This is main OnCreate() method where that perform some specific task.
Like :
Check path is Exist if no then Set Image Path .
Set Image Name as per current Date & Time.
prepare Screen View.
Draw Signature.
Store in SD Card.
Return to Activity with Bitmap Image so it can be set on Image View.
Clear Drawable Signature.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.signature);
// tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
File directory = new File(Environment.getExternalStorageDirectory() + "/Your_Floder_Name");
Check path is Exist if no then Set Image Path .
if(!directory.exists())
directory.mkdir(); //directory is created;
//prepareDirectory();
Set Image Name as per current Date & Time.
uniqueId = getTodaysDate() + "_" + getCurrentTime();
current = uniqueId + ".png";
mypath= new File(directory,current);
mContent = (LinearLayout) findViewById(R.id.linearLayout);
Draw Signature
mSignature = new signature(this, null);
mSignature.setBackgroundColor(Color.WHITE);
prepare Screen View.
mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Clear Drawable Signature.
mClear = (Button)findViewById(R.id.clear);
mGetSign = (Button)findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button)findViewById(R.id.cancel);
mView = mContent;
Clear Drawable Signature.
mClear.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
Draw Signature
mGetSign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Saved");
// boolean error = captureSignature();
// if(error){
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
//Bundle b = new Bundle();
// b.putString("status", "done");
Intent intent = new Intent(Capture.this,SigntuareCaptureActivity.class);
// intent.putExtra("imagePath",mypath);
startActivity(intent);
//intent.putExtra("status", "done");
//setResult(RESULT_OK,intent);
finish();
// }
}
});
Cancel if Don't want to Draw Signature.
mCancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Canceled");
Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();
}
});
}
Set Image Name With Current Date & Time.
private String getTodaysDate()
{
final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000) +
((c.get(Calendar.MONTH) + 1) * 100) +
(c.get(Calendar.DAY_OF_MONTH));
Log.w("DATE:",String.valueOf(todaysDate));
return(String.valueOf(todaysDate));
}
private String getCurrentTime()
{
final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000) +
(c.get(Calendar.MINUTE) * 100) +
(c.get(Calendar.SECOND));
Log.w("TIME:",String.valueOf(currentTime));
return(String.valueOf(currentTime));
}
Check Your Directory if Not Exist then Create New
private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
return false;
}
}
private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}
Draw your Signature
public class signature extends View
{
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try
{
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
//Log.v("log_tag","url: " + url);
// //In case you want to delete the file
// boolean deleted = mypath.delete();
// Log.v("log_tag","deleted: " + mypath.toString() + deleted);
// //If you want to convert the image to string use base64 converter
}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}
public void clear()
{
path.reset();
invalidate();
}
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++)
{
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string)
{
}
private void expandDirtyRect(float historicalX, float historicalY)
{
if (historicalX < dirtyRect.left)
{
dirtyRect.left = historicalX;
}
else if (historicalX > dirtyRect.right)
{
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top)
{
dirtyRect.top = historicalY;
}
else if (historicalY > dirtyRect.bottom)
{
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY)
{
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
How to call this class ?
on Click of button in main Activity ,
your_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(SigntuareCaptureActivity.this, Capture.class);
startActivity(intent);
finish();
}
});