簡體   English   中英

如何將圖像裁剪為正方形-Android?

[英]how to crop image to square - android?

所以我有一個帶有個人資料圖像的個人資料活動。 現在,垂直拍攝的圖像。 我有水平圖像視圖。 當我在onActivityResult()上獲取圖像時,如何“平方”圖像。 我要用正方形表示圖像,我希望每個圖像的寬度都等於屏幕的寬度(並且由於它是正方形,所以高度=圖像寬度=屏幕寬度)。

在onActivityResult()中,我從畫廊和相機獲得的圖像作為字符串路徑(可以轉換為位圖)返回。 另外,當我獲取圖像時,我會使用Glide庫和url從后端獲取圖像。

Glide.with(context).load("www.mybackendToImagePath").centerCrop().into(newImageView);

因此,我需要將該圖像路徑轉換為位圖,然后以某種方式將該位圖與屏幕的寬度相乘。 我不確定使用什么代碼可以執行以下操作:

  1. 獲取設備的尺寸。
  2. 將圖片的寬度和高度轉換為設備的寬度。

希望你們能提供幫助!

這是我的個人資料活動的樣子。

在此處輸入圖片說明

您可以使用此https://github.com/Yalantis/uCrop庫來裁剪從相機或圖庫中獲得的圖像。 將圖書館納入本地圖書館項目

 allprojects {
 repositories {
  jcenter()
  maven { url "https://jitpack.io" }
 }
}

添加依賴項

compile 'com.github.yalantis:ucrop:2.2.1'

要么

compile 'com.github.yalantis:ucrop:2.2.1-native'

將UCropActivity添加到您的AndroidManifest.xml中

<activity
    android:name="com.yalantis.ucrop.UCropActivity"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

現在,在以下代碼中將圖像的URI作為sourceUri傳遞,並且destinationUri將是您要放置裁剪后的圖像的位置

UCrop.of(sourceUri, destinationUri)
.withAspectRatio(1, 1)//1, 1 is the ratio b/w width and height of image i.e. square you can pass any ratio here
.withMaxResultSize(maxWidth, maxHeight)
.start(context);

覆蓋onActivityResult方法並處理uCrop結果。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        final Uri resultUri = UCrop.getOutput(data);
    } else if (resultCode == UCrop.RESULT_ERROR) {
        final Throwable cropError = UCrop.getError(data);
    }
}

暫無
暫無

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

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