簡體   English   中英

將圖像裁剪為方形 - Android

[英]Crop image to square - Android

如何從左右切割矩形圖像(600 x 300)以適合方形ImageView? 我不想調整圖像大小,我只想裁剪它,為300 x 300。

[解]

正如@blackbelt所說

Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

非常適合裁剪圖像。 那么如何自動裁剪不同尺寸的圖像。 我為此創建了這個簡單的代碼:

// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

// From URL
Bitmap src = null;
try {
    String URL = "http://www.example.com/image.jpg";
    InputStream in = new java.net.URL(URL).openStream();
    src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
    e.printStackTrace();
}

int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height) / 2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);

ImageView.setImageBitmap(cropImg);

在上面的答案上稍微擴展一下

因為在某些情況下你可以最終得到一個異常不是預期的結果 ,只需使用Bitmap.createBitmap(),就像以下一樣:

java.lang.IllegalArgumentException:x + width必須是<= bitmap.width()

Heres是一個小功能,可以完成裁剪並處理一些公共案件。

編輯:根據droidster的說法更新。

public static Bitmap cropToSquare(Bitmap bitmap){
    int width  = bitmap.getWidth();
    int height = bitmap.getHeight();
    int newWidth = (height > width) ? width : height;
    int newHeight = (height > width)? height - ( height - width) : height;
    int cropW = (width - height) / 2;
    cropW = (cropW < 0)? 0: cropW;
    int cropH = (height - width) / 2;
    cropH = (cropH < 0)? 0: cropH;
    Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);

    return cropImg;
}

我用一些不同分辨率和大小的圖像做了幾次測試,它按預期工作。

它也可以在其他情況下使用,例如當您嘗試制作“完美”的圓形圖像並需要傳遞方形位圖等時。

設置固定圖像視圖高度,寬度,並將兩個屬性設置為圖像視圖

android:adjustViewBounds="true" 
android:scaleType="centerCrop"

DONE

您可以使用

Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

從文件:

從源位圖的指定子集返回不可變位圖。 新位圖可以是與源相同的對象,也可以是副本。 它使用與原始位圖相同的密度進行初始化。

在這里您可以找到文檔

現在xml具有類似的屬性

 custom:cropAspectRatioX="2"
    custom:cropAspectRatioY="1"

如果你想要方形裁剪,請將兩者都設為1。 現在它是矩形的

添加活動CropActivity

       package agropost.post.agro.com.agropost.Activity;

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.DisplayMetrics;
    import android.widget.Button;

    import com.theartofdev.edmodo.cropper.CropImageView;

    import agropost.post.agro.com.agropost.R;
    import agropost.post.agro.com.agropost.Utility.Constants;
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.OnClick;

    public class CropActivity extends AppCompatActivity {


        public static boolean isCrop = false;
        @BindView(R.id.img_crop)
        CropImageView imgCrop;
        @BindView(R.id.btn_done)
        Button btnDone;
        @BindView(R.id.btn_cancel)
        Button btnCancel;




        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_crop);
            ButterKnife.bind(this);


            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int width = displayMetrics.widthPixels;
            width = width - 80;
            imgCrop.getLayoutParams().height = width;
            imgCrop.getLayoutParams().width = width;

            imgCrop.setBackground(null);
            imgCrop.setScaleType(CropImageView.ScaleType.FIT_CENTER);



                imgCrop.setImageBitmap(Constants.mDashboardActivity.thumbnail_r);



        }

        @OnClick(R.id.btn_done)
        public void onViewClicked() {

            isCrop = true;
            Intent returnIntent = new Intent();



                Constants.mDashboardActivity.thumbnail_r = imgCrop.getCroppedImage();
                setResult(3, returnIntent);



            finish();
        }

        @OnClick(R.id.btn_cancel)
        public void onViewClickedCancel() {

            byte[] byteArray = getIntent().getByteArrayExtra("default");
            Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);


            Constants.mDashboardActivity.thumbnail_r = bmp;
            isCrop = true;
            Intent returnIntent = new Intent();
            setResult(3, returnIntent);

            finish();
        }


       @Override
        public void onBackPressed() {
            //  super.onBackPressed();


        }


    }

xml的活動..............

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".Activity.CropActivity">


    <com.theartofdev.edmodo.cropper.CropImageView xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:id="@+id/img_crop"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/drawer_bg"
        android:scaleType="centerInside"
        custom:cropAspectRatioX="2"
        custom:cropAspectRatioY="1"
        custom:cropFixAspectRatio="true"
        custom:cropShape="rectangle" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_done"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginLeft="@dimen/margin_40"
            android:layout_marginRight="@dimen/margin_20"
            android:layout_marginTop="@dimen/margin_20"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_green_rounded"
            android:text="Done"
            android:textColor="@color/colorWhite"

            android:textSize="@dimen/fontsize_normal" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginLeft="@dimen/margin_20"
            android:layout_marginRight="@dimen/margin_40"
            android:layout_marginTop="@dimen/margin_20"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_green_rounded"
            android:text="Cancel"
            android:textColor="@color/colorWhite"
            android:textSize="@dimen/fontsize_normal"

            android:visibility="gone" />
    </LinearLayout>

</LinearLayout>

添加依賴性

      implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM