在自己应用中,从系统图库中取图片,然后截取其中一部分,再返回到自己应用中。这是很多有关图片的应用需要的功能。
写了一个示例,上来就是个大按钮,连布局都不要了。最终,用选取图片中的一部分作为按钮的背景。
这里需要注意几点:
- 从图库中选取出来保存的图片剪辑,需要保存在sd卡目录,不能保存在应用自己的在内存的目录,因为是系统图库来保存这个文件,它没有访问你应用的权限;
- intent.putExtra("crop", "true")才能出剪辑的小方框,不然没有剪辑功能,只能选取图片;
- intent.putExtra("aspectX", 1),是剪辑方框的比例,可用于强制图片的长宽比。
代码片段(2)
[图片] 2_thumb.png
[代码] [Java]代码
01 | package com.easymorse.gallery; |
02 |
03 | import java.io.File; |
04 |
05 | import android.app.Activity; |
06 | import android.content.Intent; |
07 | import android.graphics.drawable.Drawable; |
08 | import android.net.Uri; |
09 | import android.os.Bundle; |
10 | import android.view.View; |
11 | import android.view.View.OnClickListener; |
12 | import android.widget.Button; |
13 |
14 | public class GalleryActivity extends Activity { |
15 |
16 | private static int SELECT_PICTURE; |
17 |
18 | private File tempFile; |
19 |
20 | Button button; |
21 |
22 | /** Called when the activity is first created. */ |
23 | @Override |
24 | public void onCreate(Bundle savedInstanceState) { |
25 | super .onCreate(savedInstanceState); |
26 | this .tempFile= new File( "/sdcard/a.jpg" ); |
27 | button = new Button( this ); |
28 | button.setText( "获取图片" ); |
29 | button.setOnClickListener( new OnClickListener() { |
30 |
31 | @Override |
32 | public void onClick(View v) { |
33 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT); |
34 | intent.setType( "image/*" ); |
35 | intent.putExtra( "crop" , "true" ); |
36 |
37 | // intent.putExtra("aspectX", 1); |
38 | // intent.putExtra("aspectY", 2); |
39 |
40 | intent.putExtra( "output" , Uri.fromFile(tempFile)); |
41 | intent.putExtra( "outputFormat" , "JPEG" ); |
42 |
43 | startActivityForResult(Intent.createChooser(intent, "选择图片" ), |
44 | SELECT_PICTURE); |
45 | } |
46 | }); |
47 | setContentView(button); |
48 | } |
49 |
50 | @Override |
51 | protected void onActivityResult( int requestCode, int resultCode, Intent data) { |
52 | if (resultCode == RESULT_OK) { |
53 | if (requestCode == SELECT_PICTURE) { |
54 | button.setBackgroundDrawable(Drawable.createFromPath(tempFile |
55 | .getAbsolutePath())); |
56 | } |
57 | } |
58 | } |
59 |
60 | } |