在imageview android

时间:2017-05-07 07:14:05

标签: java android

我必须在图像视图中在捕获图像的中心绘制圆并保存在DB中。首先捕获图像并裁剪图像并在图像中心绘制圆圈并在图像视图中显示并保存在DB中。圆圈没有画出来。我尝试了很多方法。请帮帮我。

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:baselineAligned="false"
    tools:context=".MainActivity"
    android:weightSum="1">

    <Button
        android:id="@+id/btn_select_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="Select Image" />


    <LinearLayout
        android:layout_width="226dp"
        android:layout_height="231dp"
        android:orientation="vertical"
        android:weightSum="1">

        <ImageView
            android:id="@+id/img_photo"
            android:layout_width="200dp"
            android:layout_height="500dp"
            android:layout_marginTop="10dp"
            android:scaleType="fitXY"
            android:layout_weight="0.45" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="280dp"
        android:layout_height="77dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/xPos"
            android:layout_width="5dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.32"
            android:gravity="left|center_vertical"
            android:padding="5dip"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/yPos"
            android:layout_width="5dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.32"
            android:gravity="right|center_vertical"
            android:padding="5dip"
            android:visibility="invisible" />
    </LinearLayout>


</LinearLayout>

MainActivity.java

package knuckle.app.com.knuckleauthentication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import knuckle.app.com.knuckleauthentication.R;

import static android.R.attr.bitmap;
import static android.R.attr.color;
import static android.R.attr.path;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import android.content.Context;
import android.view.ViewGroup.LayoutParams;

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_PERMISSION_REQ_CODE = 34;
    private static final int CAMERA_CODE = 101, GALLERY_CODE = 201, CROPING_CODE = 301;
    public static final int MEDIA_TYPE_IMAGE = 1;
    // directory name to store captured images and videos
    private static final String IMAGE_DIRECTORY_NAME = "Knuckle Images";

    private Button btn_select_image;

    private TextView txt_x_pos, txt_y_pos;

        private ImageView imageView;
        private Uri mImageCaptureUri;
        private File outPutFile = null;
        private DataHelper dbHelper;
    FrameLayout preview = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            dbHelper=new DataHelper(this);
            outPutFile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");



            txt_x_pos = (TextView) findViewById(R.id.xPos);
              txt_y_pos = (TextView) findViewById(R.id.yPos);

            btn_select_image = (Button) findViewById(R.id.btn_select_image);
            imageView = (ImageView) findViewById(R.id.img_photo);

            btn_select_image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    selectImageOption();
                }
            });

        }

        private void selectImageOption() {
            final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {

                    if (items[item].equals("Capture Photo")) {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                       // File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
                        mImageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        startActivityForResult(intent, CAMERA_CODE);

                    } else if (items[item].equals("Choose from Gallery")) {

                        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, GALLERY_CODE);

                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, final @NonNull String[] permissions, final @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_REQ_CODE: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {

                mImageCaptureUri = data.getData();
                System.out.println("Gallery Image URI : "+mImageCaptureUri);
                CropingIMG();

            } else if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {

                System.out.println("Camera Image URI : "+mImageCaptureUri);
                CropingIMG();
            } else if (requestCode == CROPING_CODE) {

                try {
                    if(outPutFile.exists()){
                        Bitmap photo = decodeFile(outPutFile);
                        imageView.setImageBitmap(photo);

                      /*  BitmapFactory.Options bfo = new BitmapFactory.Options();
                        bfo.inDither = true;
                        bfo.inScaled = false;
                        bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        bfo.inPurgeable = true;

                        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.id.img_photo, bfo);
                        Paint paint = new Paint();
                        paint.setAntiAlias(true);
                        paint.setStrokeWidth(10);
                        paint.setColor(Color.RED);

                        Bitmap workingBitmap = Bitmap.createBitmap(bm);
                        Bitmap mutuableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

                        Canvas canvas = new Canvas(mutuableBitmap);
                        canvas.drawCircle(60, 50, 15, paint);
                        imageView.setAdjustViewBounds(true);
                        imageView.setImageBitmap(mutuableBitmap);*/
                       //

                       // preview.addView(imageView);

                      //  Display display = getWindowManager().getDefaultDisplay();
                        //Point size = new Point(photo.getHeight()/2, photo.getWidth()/2);
                        //display.getSize(size);
                       // int screenCenterX = (size.x/2);
                        //int screenCenterY = (size.y/2) ;
                        //DrawOnTop mDraw = new DrawOnTop(this,screenCenterX,screenCenterY);
                        //addContentView(mDraw, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                       //  txt_x_pos.setText(screenCenterX);
                        // txt_y_pos.setText(screenCenterY);

                        createBitMap();
                        dbHelper.insertBitmap(photo);

                        Toast.makeText(getApplicationContext(),
                                "Knuckle Image Saved successfully.",
                                Toast.LENGTH_LONG).show();

                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Error while save image", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    private void createBitMap() {

        Bitmap bitMap = BitmapFactory.decodeResource(null, R.id.img_photo);  //creates bmp
        bitMap = bitMap.copy(bitMap.getConfig(), true);     //lets bmp to be mutable
        Canvas canvas = new Canvas(bitMap);                 //draw a canvas in defined bmp

        Paint paint = new Paint();                          //define paint and paint color
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(15);
        paint.setAntiAlias(true);                           //smooth edges

        Display display = getWindowManager().getDefaultDisplay();
        int centerX = display.getWidth()/2;
        int centerY = display.getHeight()/2;

        float canvasX = (float) canvas.getWidth();
        float canvasY = (float) canvas.getHeight();

        float bitmapX = (float) bitMap.getWidth();
        float bitmapY = (float) bitMap.getHeight();

        float boardPosX = ((canvasX/2) - (bitmapX/2));
        float boardPosY = ((canvasY /2)- (bitmapY/2));

        canvas.drawBitmap(bitMap, boardPosX, boardPosY, paint);

        canvas.drawCircle(centerX, centerY, 3, paint);

        imageView.setImageBitmap(bitMap);
    }
        private void CropingIMG() {

            final ArrayList<CropingOption> cropOptions = new ArrayList<CropingOption>();

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setType("image/*");

            List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();
            if (size == 0) {
                Toast.makeText(this, "Cann't find image croping app", Toast.LENGTH_SHORT).show();
                return;
            } else {
                intent.setData(mImageCaptureUri);
                intent.putExtra("outputX", 512);
                intent.putExtra("outputY", 512);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);

                //TODO: don't use return-data tag because it's not return large image data and crash not given any message
                //intent.putExtra("return-data", true);

                //Create output file here
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

                if (size == 1) {
                    Intent i   = new Intent(intent);
                    ResolveInfo res = (ResolveInfo) list.get(0);

                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                    startActivityForResult(i, CROPING_CODE);
                } else {
                    for (ResolveInfo res : list) {
                        final CropingOption co = new CropingOption();

                        co.title  = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon  = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);
                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                        cropOptions.add(co);
                    }

                    CropingOptionAdapter adapter = new CropingOptionAdapter(getApplicationContext(), cropOptions);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Choose Croping App");
                    builder.setCancelable(false);
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        public void onClick( DialogInterface dialog, int item ) {
                            startActivityForResult( cropOptions.get(item).appIntent, CROPING_CODE);
                        }
                    });

                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {

                            if (mImageCaptureUri != null ) {
                                getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );

                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }

        private Bitmap decodeFile(File f) {
            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                // Find the correct scale value. It should be the power of 2.
                final int REQUIRED_SIZE = 512;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
            }
            return null;
        }
    /**
     * ------------ Helper Methods ----------------------
     * */

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
        }
    }


class DrawOnTop extends View {
    int screenCenterX = 0;
    int screenCenterY = 0;
    final int radius = 15;
    public DrawOnTop(Context context, int screenCenterX, int screenCenterY) {
        super(context);
        this.screenCenterX = screenCenterX;
        this.screenCenterY = screenCenterY;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        Paint p = new Paint();
        p.setColor(Color.RED);
        DashPathEffect dashPath = new DashPathEffect(new float[]{5,5}, (float)1.0);
        p.setPathEffect(dashPath);
        p.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(screenCenterX, screenCenterY, radius, p);
        invalidate();
        super.onDraw(canvas);
    }
}

CroppingOption.java

package knuckle.app.com.knuckleauthentication;

import android.content.Intent;
import android.graphics.drawable.Drawable;

/**
 * Created by DP on 7/12/2016.
 */
public class CropingOption {
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;
}

CroppingOptionAdapter.java

package knuckle.app.com.knuckleauthentication;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import knuckle.app.com.knuckleauthentication.R;
import android.support.v7.app.AppCompatActivity;


public class CropingOptionAdapter extends ArrayAdapter {
    private ArrayList mOptions;
    private LayoutInflater mInflater;

    public CropingOptionAdapter(Context context, ArrayList options) {
        super(context, R.layout.croping_selector, options);

        mOptions  = options;

        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup group) {
        if (convertView == null)
            convertView = mInflater.inflate(R.layout.croping_selector, null);

        CropingOption item = (CropingOption) mOptions.get(position);

        if (item != null) {
            ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
            ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

            return convertView;
        }

        return null;
    }
}

Datahelper.java

package knuckle.app.com.knuckleauthentication;

import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class DataHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "knuckledb";
    public static final String TABLE_NAME = "tbl_knuckle_img";
    public static final int DATABASE_VERSION = 1;
    public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, img BLOB NOT NULL, description TEXT NULL)";
    public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public DataHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    public void onCreate(SQLiteDatabase db) {
        // Create the table
        db.execSQL(CREATE_TABLE);

    }

    //Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop older table if existed
        db.execSQL(DELETE_TABLE);
        //Create tables again
        onCreate(db);
    }

    public void insertBitmap(Bitmap bm) {

        // Convert the image into byte array
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, out);
        byte[] buffer = out.toByteArray();
        // Open the database for writing
        SQLiteDatabase db = this.getWritableDatabase();
        // Start the transaction.
        db.beginTransaction();
        ContentValues values;
        int width=bm.getWidth();
        int height=bm.getHeight();

        int centerX=width/2;
        int centerY=height/2;

        try {
            values = new ContentValues();
            values.put("img", buffer);
            values.put("description", "knuckle image");
            values.put("centerX", centerX);
            values.put("centerY", centerY);
            // Insert Row
            long i = db.insert(TABLE_NAME, null, values);
            Log.i("Insert", i + "");
            // Insert into database successfully.
            db.setTransactionSuccessful();

        } catch (SQLiteException e) {
            e.printStackTrace();

        } finally {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
    }

    public Bitmap getBitmap(int id) {
        Bitmap bitmap = null;
        // Open the database for reading
        SQLiteDatabase db = this.getReadableDatabase();
        // Start the transaction.
        db.beginTransaction();

        try {
            String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE id = " + id;
            Cursor cursor = db.rawQuery(selectQuery, null);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    // Convert blob data to byte array
                    byte[] blob = cursor.getBlob(cursor.getColumnIndex("img"));
                    // Convert the byte array to Bitmap
                    bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);

                }

            }
            db.setTransactionSuccessful();

        } catch (SQLiteException e) {
            e.printStackTrace();

        } finally {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
        return bitmap;

    }

}

1 个答案:

答案 0 :(得分:0)

你想要像这个链接中那样绘制图像

[画圆圈图片] https://github.com/youssefshaaban/Show-Round-Image-from-Webservice

您可以在应用中使用文件RoundedImageView.java并在XMl Layout中使用它而不是ImageView