android调用系统资源裁剪图片

来源:互联网 发布:俄罗斯方块 软件测试 编辑:程序博客网 时间:2024/05/16 07:53

1 import java.io.File;
2 import android.app.Activity;
3 import android.content.Intent;
4 import android.graphics.drawable.Drawable;
5 import android.net.Uri;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.view.View.OnClickListener;
9 import android.widget.Button;
10
11 public class GalleryActivity extends Activity {
12
13     private static int SELECT_PICTURE;//返回标志位 filed
14
15     private File tempFile;
16
17     Button button;
18
19     /** Called when the activity is first created. */
20     @Override
21     public void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         this.tempFile = new File("/sdcard/a.jpg");// 这句一定要在onCreate()里面调用
24         button = new Button(this);
25         button.setText("获取图片");
26         button.setOnClickListener(new OnClickListener() {
27             @Override
28             public void onClick(View v) {
29                 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
30                 intent.setType("image/*");
31                 intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
32
33                 intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
34                 intent.putExtra("aspectY", 2);// x:y=1:2
35
36                 intent.putExtra("output", Uri.fromFile(tempFile));
37                 intent.putExtra("outputFormat", "JPEG");//返回格式
38
39                 startActivityForResult(Intent.createChooser(intent, "选择图片"), SELECT_PICTURE);
40             }
41         });
42         setContentView(button);
43     }
44
45     /**
46      * 裁剪完图片后系统调用的方法:onActivityResult
47      */
48     @Override
49     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
50         if (resultCode == RESULT_OK)
51             if (requestCode == SELECT_PICTURE)
52                 button.setBackgroundDrawable(Drawable.createFromPath(tempFile.getAbsolutePath()));
53     }
54 }