裁剪自定义形状图像时出错

时间:2014-12-08 08:26:37

标签: java android bitmap

(JAVA FILE 1)

public class CropActivity extends Activity implements OnTouchListener {
    public static final String RETURN_DATA = "return-data";
    public static final String RETURN_DATA_AS_BITMAP = "data";
    public static final String ACTION_INLINE_DATA = "inline-data";
    private ImageView mImg;
    private ImageView mTemplateImg;
    // private static ProgressDialog mProgressDialog;
    private Matrix mMatrix = new Matrix();
    private float mScaleFactor = 0.8f;
    private float mRotationDegrees = 0.f;
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;
    private int mImageHeight, mImageWidth;
    private ScaleGestureDetector mScaleDetector;
    private MoveGestureDetector mMoveDetector;

    // Constants
    public static final int MEDIA_GALLERY = 1;
    public static final int TEMPLATE_SELECTION = 2;
    public static final int DISPLAY_IMAGE = 3;
    Bitmap profilePic;
    String userImageLink;
    int cropImageWidth;
    int cropImageHeight;
    int width, height, w1;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.crop_activity_layout);
        Resources r = getResources();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;

        double fWidth = width * (0.70);

        Log.d("Width is:- ", ">>>>>>>>>>>>>>>>" + fWidth);

        w1 = (int) Math.round(fWidth);

        Log.d("Width after roundin is:- ", ">>>>>>>>>>>>>>>>" + width);
        cropImageWidth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, w1, r.getDisplayMetrics());
        // etc...
        cropImageHeight = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, w1, r.getDisplayMetrics());

        int actionBarHeight = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 40, r.getDisplayMetrics());

        userImageLink = getIntent().getStringExtra("path");

        mImg = (ImageView) findViewById(R.id.cp_img);
        mTemplateImg = (ImageView) findViewById(R.id.cp_face_template);
        mImg.setOnTouchListener(this);
        // Get screen size in pixels.
        // DisplayMetrics metrics = new DisplayMetrics();
        // getWindowManager().getDefaultDisplay().getMetrics(metrics);
        // mScreenWidth = metrics.widthPixels;
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int statusBarHeight = (int) Math.ceil(25 * (getResources()
                .getDisplayMetrics().density));
        Log.e("size.x", "" + size.x);
        Log.e("size.y", "" + (size.y - statusBarHeight - actionBarHeight));
        // Set template image accordingly to device screen size.
        Bitmap faceTemplate = BitmapFactory.decodeResource(getResources(),
                R.drawable.four);
        faceTemplate = Bitmap.createScaledBitmap(faceTemplate, cropImageWidth,
                cropImageHeight, true);
        mTemplateImg.setImageBitmap(faceTemplate);
        // cropImageWidth = faceTemplate.getWidth();
        // cropImageHeight = faceTemplate.getHeight();
        // Log.e("getWidth", "" + faceTemplate.getWidth());
        // Log.e("getHeight", "" + faceTemplate.getHeight());

        File imgFile = new File("" + userImageLink);
        if (imgFile.exists()) {
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
                    .getAbsolutePath());
            // Drawable d = new BitmapDrawable(getResources(), myBitmap);

            mImg.setImageBitmap(myBitmap);
            mImageHeight = myBitmap.getHeight();
            mImageWidth = myBitmap.getWidth();
        }
        // View is scaled by matrix, so scale initially
        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mImg.setImageMatrix(mMatrix);

        // Setup Gesture Detectors
        mScaleDetector = new ScaleGestureDetector(getApplicationContext(),
                new ScaleListener());
        mMoveDetector = new MoveGestureDetector(getApplicationContext(),
                new MoveListener());

        // Instantiate Thread Handler.
        // mCropHandler = new CropHandler(this);

    }
    public void onCancelImageButton(View v) {
        Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
    }
    public void onCropImageButton(View v) {
        // Create progress dialog and display it.
        // mProgressDialog = new ProgressDialog(v.getContext());
        // mProgressDialog.setCancelable(false);
        // mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        // mProgressDialog.setMessage("Please wait...");
        // mProgressDialog.show();

        // Setting values so that we can retrive the image from
        // ImageView multiple times.
        mImg.buildDrawingCache(true);
        mImg.setDrawingCacheEnabled(true);
        mTemplateImg.buildDrawingCache(true);
        mTemplateImg.setDrawingCacheEnabled(true);
        // Create new thread to crop.
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap croppedImg = null;
                croppedImg = ImageProcess.cropImage(mImg.getDrawingCache(true),
                        mTemplateImg.getDrawingCache(true), cropImageWidth,
                        cropImageHeight);

                mImg.setDrawingCacheEnabled(false);
                mTemplateImg.setDrawingCacheEnabled(false);
                if (croppedImg != null) {
                    // mProgressDialog.dismiss();

                    Utils.storeImage(croppedImg, "temp" + Const.ImageExtension);

                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    // mProgressDialog.dismiss();
                    Intent intent = new Intent();
                    setResult(RESULT_CANCELED, intent);
                    finish();
                }
            }
        }).start();
    }
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouch(View v, MotionEvent event) {
        mScaleDetector.onTouchEvent(event);

        mMoveDetector.onTouchEvent(event);

        float scaledImageCenterX = (mImageWidth * mScaleFactor) / 2;
        float scaledImageCenterY = (mImageHeight * mScaleFactor) / 2;

        mMatrix.reset();
        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mMatrix.postRotate(mRotationDegrees, scaledImageCenterX,
                scaledImageCenterY);
        mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY
                - scaledImageCenterY);

        ImageView view = (ImageView) v;
        view.setImageMatrix(mMatrix);
        return true;
    }
    private class ScaleListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));

            return true;
        }
    }
    private class MoveListener extends
            MoveGestureDetector.SimpleOnMoveGestureListener {
        @Override
        public boolean onMove(MoveGestureDetector detector) {
            PointF d = detector.getFocusDelta();
            mFocusX += d.x;
            mFocusY += d.y;

            return true;
        }
    }
}

(JAVA FILE 2)

public class ImageProcess {
    public static Bitmap cropImage(Bitmap img, Bitmap templateImage, int width,
            int height) {
        // Merge two images together.
        Bitmap bm = Bitmap.createBitmap(img.getWidth(), img.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas combineImg = new Canvas(bm);
        combineImg.drawBitmap(img, 0f, 0f, null);
        // Create new blank ARGB bitmap.
        Bitmap finalBm = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // Get the coordinates for the middle of combineImg.
        int hMid = bm.getHeight() / 2;
        int wMid = bm.getWidth() / 2;
        int hfMid = finalBm.getHeight() / 2;
        int wfMid = finalBm.getWidth() / 2;

        finalBm = Bitmap.createBitmap(bm, (wMid - wfMid), (hMid - hfMid),
                width, height);

        // Get rid of images that we finished with to save memory.
        img.recycle();
        templateImage.recycle();
        bm.recycle();
        return finalBm;
    }
}

(XML文件1)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <innovify.hustl.library.CustomTextView
        android:id="@+id/fcp_info_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/cp_info_text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:visibility="gone" />

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1.0" >

        <ImageView
            android:id="@+id/cp_img"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:contentDescription="@string/cp_image_contentDesc"
            android:scaleType="matrix" />

        <ImageView
            android:id="@+id/cp_face_template"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:contentDescription="@string/cp_template_contentDesc"
            android:scaleType="centerInside"
            android:src="@drawable/four" />
    </FrameLayout>

    <LinearLayout
        style="?android:attr/buttonBarStyle"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:orientation="horizontal" >

        <innovify.hustl.library.CustomButton
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#e2e2e2"
            android:gravity="center"
            android:onClick="onCancelImageButton"
            android:text="@string/cancel" />

        <innovify.hustl.library.CustomButton
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="#e2e2e2"
            android:gravity="center"
            android:onClick="onCropImageButton"
            android:text="@string/cp_crop_button" />


</LinearLayout>

输出:

出现此错误: -

12-08 13:35:38.108: E/AndroidRuntime(15191): FATAL EXCEPTION: Thread-1317
12-08 13:35:38.108: E/AndroidRuntime(15191): java.lang.IllegalArgumentException: x must be >= 0
12-08 13:35:38.108: E/AndroidRuntime(15191):    at android.graphics.Bitmap.checkXYSign(Bitmap.java:280)
12-08 13:35:38.108:

1 个答案:

答案 0 :(得分:1)

用于imageview中的自定义形状,

你可以使用这个lib

https://github.com/siyamed/android-shape-imageview    https://github.com/MostafaGazar/CustomShapeImageView