可选择的圆形图像视图,如 Google+

Selectable circular imageview like Google+(可选择的圆形图像视图,如 Google+)

本文介绍了可选择的圆形图像视图,如 Google+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个可选择的圆形 ImageView,就像当前用于个人资料图片的 Google+ 应用程序一样?

How can I create a selectable circular ImageView like in the current Google+ app used for the profile pictures?

这就是我所指的:

上图未选中,下图已选中.

The image above is unselected and the below is selected.

我尝试一一复制个人资料图片.

I try to replicate the profile pictures 1 to 1.

我目前的工作:

loadedImage 是显示的Bitmap

mImageView.setBackground(createStateListDrawable());
mImageView.setImageBitmap(createRoundImage(loadedImage));

使用的方法:

private Bitmap createRoundImage(Bitmap loadedImage) {
    Bitmap circleBitmap = Bitmap.createBitmap(loadedImage.getWidth(), loadedImage.getHeight(), Bitmap.Config.ARGB_8888);

    BitmapShader shader = new BitmapShader(loadedImage, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);

    Canvas c = new Canvas(circleBitmap);
    c.drawCircle(loadedImage.getWidth() / 2, loadedImage.getHeight() / 2, loadedImage.getWidth() / 2, paint);

    return circleBitmap;
}

private StateListDrawable createStateListDrawable() {
    StateListDrawable stateListDrawable = new StateListDrawable();

    OvalShape ovalShape = new OvalShape();
    ShapeDrawable shapeDrawable = new ShapeDrawable(ovalShape);
    stateListDrawable.addState(new int[] { android.R.attr.state_pressed }, shapeDrawable);
    stateListDrawable.addState(StateSet.WILD_CARD, shapeDrawable);

    return stateListDrawable;
}

ImageView的大小是imageSizePx,图片的大小是imageSizePx - 3.所以,这意味着背景应该与图像重叠.哪个不行.

The size of the ImageView is imageSizePx and the size of the image is imageSizePx - 3. So, that means the background should overlap the image. Which doesn't work.

推荐答案

非常简单的解决方案,感谢@CommonsWare 的提示.

Really simple solution, thanks to @CommonsWare for the tips.

Bitmap的大小:imageSizePx - 3DP
ImageView的大小:imageSizePx

Size of Bitmap: imageSizePx - 3DP
Size of ImageView: imageSizePx

mImageView.setBackground(createStateListDrawable(imageSizePx));
mImageView.setImageBitmap(loadedImage);

private StateListDrawable createStateListDrawable(int size) {
    StateListDrawable stateListDrawable = new StateListDrawable();

    OvalShape ovalShape = new OvalShape();
    ovalShape.resize(size, size);
    ShapeDrawable shapeDrawable = new ShapeDrawable(ovalShape);
    shapeDrawable.getPaint().setColor(getResources().getColor(R.color.somecolor));

    stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, shapeDrawable);
    stateListDrawable.addState(new int[]{android.R.attr.state_focused}, shapeDrawable);
    stateListDrawable.addState(new int[]{}, null);

    return stateListDrawable;
}

这篇关于可选择的圆形图像视图,如 Google+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:可选择的圆形图像视图,如 Google+

基础教程推荐