如果我們想要的是1:1的圖片呢?怎麼辦?拿剪刀?從手機讀出來用圖片編輯軟體
裁剪後再放回去?當然不是這樣的,這樣太麻煩了,如果能直接裁剪當然是最好的
所以下面就為您介紹直接在取得圖檔時就執行裁剪圖片的動作。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/b01"
android:layout_width="fill_parent"
android:layout_height="wrap_content&
/>
<ImageView
android:id="@+id/iv01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
GetPicturesActivity.java
package jim.demo.getpictures;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class GetPicturesActivity extends Activity {
private File tempFile;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.tempFile = new File("/sdcard/a.jpg");// 這句一定要在onCreate()里面調用
//找尋Button按鈕
Button button = (Button)findViewById(R.id.b01);
//設定按鈕內文字
button.setText("選擇圖片");
//設定按鈕監聽式
button.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent();
// 開啟Pictures畫面Type設定為image
intent.setType("image/*");
// 使用Intent.ACTION_GET_CONTENT這個Action
// 會開啟選取圖檔視窗讓您選取手機內圖檔
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true");// crop=true 有這句才能叫出裁剪頁面.
intent.putExtra("aspectX", 1);// 这兩項為裁剪框的比例.
intent.putExtra("aspectY", 1);// x:y=1:1
intent.putExtra("output", Uri.fromFile(tempFile));
intent.putExtra("outputFormat", "JPEG");//返回格式
// 取得相片後返回本畫面
startActivityForResult(Intent.createChooser(intent, "選擇圖片"),1);
}
});
}
//取得相片後返回的監聽式
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//取得圖片控制項ImageView
ImageView imageView = (ImageView) findViewById(R.id.iv01);
//當使用者按下確定後
if (resultCode == RESULT_OK) {
// 設定到ImageView
imageView.setImageDrawable(Drawable.createFromPath(tempFile.getAbsolutePath()));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
執行畫面
後記:
切割其實是使用intent.setAction(Intent.ACTION_GET_CONTENT)抓取圖片後
再多加一個動作使用intent.putExtra("crop", "true")叫出裁剪頁面達到裁剪效果
還蠻簡單的,下篇再為您介紹在拍照後如果要裁剪照片該怎麼做,感謝收看。




您好!請問剪裁的部分是否可以改為不規則圖片的外框呢?
回覆刪除請問有相關建議的方法嗎?
謝謝您!
沒有辦法喔
刪除您好!請問剪裁的部分是否可以改為不規則圖片的外框呢?
回覆刪除請問有相關建議的方法嗎?
謝謝您!
沒辦法喔,用PS軟體修吧
刪除public void onClick(View v) {
回覆刪除Intent intent = new Intent();
startActivityForResult(Intent.createChooser(intent, "選擇圖片"),1);
}
我只有這樣他也讓我切