Android写真+切り取り+アルバム取得写真+透かし機能【完全】

16892 ワード

1 写真の切り取り
原理としては、intentを通じてシステムのカメラを呼び出し、写真を撮った後、再度調整して操作し、写真を撮り終わった画像はuri呼び出しシステムの裁断ページに基づいて取得し、裁断した後も折り返しで処理し、画面のイメージビューに表示される.
2 アルバムの写真を切り取ります.
原理は、intentを通じてシステムの画像を開き、ユーザーが選択した後、フィードバックで画像のuriからシステムの裁断ページを呼び出し、裁断後、コールバックで処理し、このページのコントロールに表示することです.
3コードの展示を行います.
佳娊1:Xmlレイアウトファイルにあります.


    
    

    

佳姝2:在MainActivity中

public class MainActivity extends AppCompatActivity {

    //     
    private CircleImageView main_icon;
    private Button main_btn;
    private PopWindow mpopWindow;
    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_SMALL_IMAGE_CUTTING = 2;
    private static final int REQUEST_BIG_IMAGE_CUTTING = 3;
    private static final String IMAGE_FILE_NAME = "icon.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //                        
        initView();
    }
    
    //          ( Fragment    )
    private Bitmap createWatermark(Bitmap bitmap, String mark) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        Paint p = new Paint();
        //     
        p.setColor(Color.parseColor("#c5576370"));
        //       
        p.setTextSize(40);
        //   
        p.setAntiAlias(true);
        //    
        canvas.drawBitmap(bitmap, 0, 0, p);
        //    
        canvas.drawText(mark, 0, h / 2, p);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bmp;
    }

    private void initView() {
        main_icon = (CircleImageView) findViewById(R.id.main_icon);
        main_btn = (Button) findViewById(R.id.main_btn);

        main_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpopWindow = new PopWindow(MainActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //    
                        mpopWindow.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                       //             Intent   Activity
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(intent, REQUEST_IMAGE_GET);
                        } else {
                            Toast.makeText(MainActivity.this, "        ", Toast.LENGTH_SHORT).show();
                        }
                    }

                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //    
                        mpopWindow.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                           Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));                         
                        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                    }

                });
                View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
                mpopWindow.showAtLocation(rootView,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
    }

    //           
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //     
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                //     
                case REQUEST_SMALL_IMAGE_CUTTING:
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;

                //     
                case REQUEST_IMAGE_GET:
                    try {
                        startSmallPhotoZoom(data.getData());
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                    break;
                //   
                case REQUEST_IMAGE_CAPTURE:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);
                    startSmallPhotoZoom(Uri.fromFile(temp));
                    break;
            }
        }
    }
    
    //       
    private void startSmallPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1); //      
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300); //       
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_SMALL_IMAGE_CUTTING);
    }
    
   //        
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data"); //            bitmap
            //    smallIcon    
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String storage = Environment.getExternalStorageDirectory().getPath();
                File dirFile = new File(storage + "/smallIcon");
                if (!dirFile.exists()) {
                    if (!dirFile.mkdirs()) {
                        Log.e("TAG", "       ");
                    } else {
                        Log.e("TAG", "       ");
                    }
                }
                File file = new File(dirFile, System.currentTimeMillis() + ".jpg");
                //     
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //         (    )
            // main_icon.setImageBitmap(photo);

            //         (    )
            Bitmap bitmap = createWatermark(photo, "        ");
            main_icon.setImageBitmap(bitmap);
        }
    }
 佳娊3:カスタムタイプPopoWindow継承PopWindow
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;

public class PopWindow extends PopupWindow {
    private View mView; // PopupWindow     
    private Context mContext;
    private View.OnClickListener mSelectListener; //           
    private View.OnClickListener mCaptureListener; //         
    private Button icon_btn_camera;
    private Button icon_btn_select;
    private Button icon_btn_cancel;


    public PopWindow(Activity context, View.OnClickListener selectListener, View.OnClickListener captureListener) {
        super(context);
        this.mContext = context;
        this.mSelectListener = selectListener;
        this.mCaptureListener = captureListener;
        initView();
    }

    private void initView() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
        mView = inflater.inflate(R.layout.layout_pop_xml, null);
        icon_btn_camera = (Button) mView.findViewById(R.id.icon_btn_camera);
        icon_btn_select = (Button) mView.findViewById(R.id.icon_btn_select);
        icon_btn_cancel = (Button) mView.findViewById(R.id.icon_btn_cancel);
        icon_btn_camera.setOnClickListener(mCaptureListener);
        icon_btn_select.setOnClickListener(mSelectListener);
        icon_btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        this.setContentView(mView);

        //     
        this.setAnimationStyle(R.style.popwindow_anim_style);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        //     
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x0000000);
        this.setBackgroundDrawable(dw);
        //               
        mView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height = mView.findViewById(R.id.ll_pop).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }
} 
 佳娊4:PupWindowレイアウトの中でlayout_pop_xml.xml

    
        

 @drawable/shape_item1:



   
   
   

 @drawable/shape_item2:



   
            android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />/>
            android:width="0dp"
        android:color="@android:color/white">

 @drawable/shape_item3:



   
            android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="0dp" />/>
            android:width="0dp"
        android:color="@android:color/white">

佳姝5:自定义类CircleImageView继承ImageView

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

@SuppressLint("AppCompatCustomView")
public class CircleImageView extends ImageView {

    private Paint mpaint; //  
    private int mreadius; //       
    private float mscale; //       

    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //       ,      
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        int size=Math.min(getMeasuredWidth(),getMeasuredHeight());
        mreadius=size/2;
        setMeasuredDimension(size,size);
    }
    //  
    @Override
    protected void onDraw(Canvas canvas) {
        mpaint=new Paint();
        Bitmap bitmap=drawableToBitmap(getDrawable());
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        mscale=(mreadius * 2.0f)/Math.min(bitmap.getHeight(),bitmap.getWidth());

        Matrix matrix = new Matrix();
        matrix.setScale(mscale,mscale);
        bitmapShader.setLocalMatrix(matrix);

        mpaint.setShader(bitmapShader);

        canvas.drawCircle(mreadius,mreadius,mreadius,mpaint);

    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }
}
 佳娊6:res/anim/popup_gone.xml


    
 res/anim/popup_show.xml


    
 佳娊7:values/colors中
#40cab3
 values/styleでは
 コードがそろっています.これもメモをするのに便利です.簡単ですが、いくつかの判断があるかもしれません.