首页 > 解决方案 > 从图库中获取图像并设置为 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();

另外,加载图像后,它会自动调整大小以适应圆形图像视图吗?如果不是我该怎么办?提前致谢

标签: androidimageviewsetbackground

解决方案


改用Glidewith并将您的设置为一个圆圈ImageView,如关注CircleImageViewBitmap

步骤 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);

就是这样


推荐阅读