一、效果图
二、简介
图片选择框架 Matisse 的使用,实现图片的选择及使用相机进行拍摄,最后将选择或拍摄的照片显示在 activity 中。
三、实战
1. 添加依赖
- 根目录 build.gradle 添加
allprojects {
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io"}
jcenter()
}
}
- app 目录 build.gradle 添加
implementation 'com.zhihu.android:matisse:0.5.2-beta4'
// glide
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'com.tbruyelle.rxpermissions2:rxpermissions:+'
2. AndroidManifest.xml 文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hk.matisseactivity">
<!-- 添加权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MatisseActivity">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 添加provider -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.hk.matisseactivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
</manifest>
3. filepaths.xml 文件
<resources>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="mq_DCIM" path="DCIM/camerademo" />
<external-path name="mq_Pictures" path="Pictures/camerademo" />
<files-path name="mq_private_files" path="images" />
<cache-path name="mq_private_cache" path="images" />
<external-files-path name="mq_external_files" path="Pictures" />
<external-cache-path name="mq_external_cache" path="" />
<root-path name="mq_external_cache" path="" />
</paths>
</resources>
4. GlideLoadEngine.java
/**
* Created on 2021/7/20 18:46
*
* @author Gong Youqiang
*/
public class GlideLoadEngine implements ImageEngine {
/**
* Load thumbnail of a static image resource.
*
* @param context Context
* @param resize Desired size of the origin image
* @param placeholder Placeholder drawable when image is not loaded yet
* @param imageView ImageView widget
* @param uri Uri of the loaded image
*/
public void loadThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView, Uri uri) {
Glide.with(context)
.asBitmap() // some .jpeg files are actually gif
.load(uri)
.apply(new RequestOptions()
.override(resize, resize)
.placeholder(placeholder)
.centerCrop())
.into(imageView);
}
public void loadGifThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView,
Uri uri) {
Glide.with(context)
.asBitmap() // some .jpeg files are actually gif
.load(uri)
.apply(new RequestOptions()
.override(resize, resize)
.placeholder(placeholder)
.centerCrop())
.into(imageView);
}
public void loadImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) {
Glide.with(context)
.load(uri)
.apply(new RequestOptions()
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.fitCenter())
.into(imageView);
}
public void loadGifImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) {
Glide.with(context)
.asGif()
.load(uri)
.apply(new RequestOptions()
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.fitCenter())
.into(imageView);
}
public boolean supportAnimatedGif() {
return true;
}
}
5. 逻辑代码
public class MainActivity extends BaseActivity {
private final int REQUEST_CODE_CHOOSE_PHOTO_ALBUM = 1;
private static final String[] permissionsGroup = new String[]{
Manifest.permission.CAMERA
,Manifest.permission.WRITE_EXTERNAL_STORAGE
,Manifest.permission.READ_EXTERNAL_STORAGE};
(R.id.iv_photo)
ImageView mImageView;
public int getLayoutId() {
return R.layout.activity_main;
}
public void initView() {
initPermission();
}
(R.id.btn_select_pic)
public void click() {
selectPic();
}
("MissingSuperCall")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_CHOOSE_PHOTO_ALBUM && resultCode == RESULT_OK)
{
//图片路径 同样视频地址也是这个 根据requestCode
List<Uri> pathList = Matisse.obtainResult(data);
for (Uri _Uri : pathList) {
Glide.with(this).load(_Uri).into(mImageView);
System.out.println(_Uri.getPath());
}
}
}
private void selectPic() {
Matisse.from(this)
.choose(MimeType.ofImage(), false)
.capture(true) // 使用相机,和 captureStrategy 一起使用
.captureStrategy(new CaptureStrategy(true, "com.hk.matisseactivity"))
// R.style.Matisse_Zhihu (light mode)
// R.style.Matisse_Dracula (dark mode)
.theme(R.style.Matisse_Dracula)
.countable(true)
.maxSelectable(1)
.addFilter(new Filter() {
protected Set<MimeType> constraintTypes() {
return new HashSet<MimeType>() {{
add(MimeType.PNG);
}};
}
public IncapableCause filter(Context context, Item item) {
try {
InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
int width = options.outWidth;
int height = options.outHeight;
// if (width >= 500)
// return new IncapableCause("宽度超过500px");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
})
// .gridExpectedSize((int) getResources().getDimension(R.dimen.imageSelectDimen))
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
.thumbnailScale(0.87f)
.imageEngine(new GlideLoadEngine())
.forResult(REQUEST_CODE_CHOOSE_PHOTO_ALBUM);
}
private void initPermission(){
new RxPermissions(this)
.request(permissionsGroup)
.subscribe(new Observer<Boolean>() {
public void onSubscribe( Disposable d) {
}
public void onNext(Boolean aBoolean) {
Log.d("amy", "onNext: "+aBoolean);
}
public void onError(Throwable e) {
}
public void onComplete() {
}
});
}
}