android - 从图库中获取图像并设置为 CircleImageView
问题描述
所以我在一个片段中,我想从图库中获取图像并设置为 CircleImageView。我开始了一个意图并正确选择了图像,但是在 onActivityResult 上没有设置图像。保留默认的 src 图像。这是代码
片段布局
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/photo"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/ic_launcher_background"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
/>
片段类
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.fragment_profile,container,false);
mContext = getActivity();
mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_photo);
view.findViewById(R.id.profile_photo).setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.profile_photo:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
try {
i.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0 && resultCode == Activity.RESULT_OK){
try {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("return-data");
mProfilePhoto.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
实现这个片段的活动有它的 onActivityResult,只需要调用 super();
另外,加载图像后,它会自动调整大小以适应圆形图像视图吗?如果不是我该怎么办?提前致谢
解决方案
改用Glide
with并将您的设置为一个圆圈ImageView
,如关注CircleImageView
Bitmap
步骤 1.添加依赖项
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}
步骤 2.从数据中获取位图并放入图像视图
Bitmap photo = (Bitmap) data.getExtras().get("return-data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.apply(RequestOptions.circleCropTransform())
.into(imageView);
就是这样
推荐阅读
- java - 无法在 sql server 结果集元数据中获取列名和列标签
- docker - Docker vs wsl2 资源利用率
- excel - VBA:如何遍历相同长度的多个变体数组并将它们转换为对象
- ruby - 滚动时如何检查页面底部是否到达
- flutter - 如何在颤动中更改 showDateRangePicker() 或 showDateRangePicker() 的 TextStyle
- ios - VC 和 swiftUI 的实际 UIAppearance 限制?
- ios - 在 iOS 中上传之前如何检查 PDF 大小?
- javascript - 关于 Phaser 3 中的自定义类
- delphi - 使用多条记录打开查询后减少内存使用量
- python - 基于相等大小的分组设置列值