android - 可选择的圆形 ImageView ,如 Google+

标签 android graphics imageview

我如何创建一个可选的循环ImageView,就像在当前用于个人资料图片的 Google+ 应用中一样?

我指的是:

Example

上面的图片是未选中的,下面是选中的。

我尝试 1 对 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。所以,这意味着背景应该与图像重叠。哪个不起作用。

最佳答案

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

位图的大小:imageSizePx - 3DP
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;
}

关于android - 可选择的圆形 ImageView ,如 Google+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16922732/

相关文章:

java - Java swing 中图形的标记

Android 将TableLayout 和LinearLayout 一起添加?

ios - UIImageView 不显示来自 UITableViewController 的设置图像

android - 所有设备都支持 OpenGL 吗?

php - 保护 php api 以在 android 应用程序中使用

android - 无法在 VS2015 Android 模拟器中安装 android 设备

Android ViewPager2 setPageMargin 未解决

c++ - 最佳 GPU 性能的理想位图大小?

android - 使用 ImageView 显示 AlertDialog 而无需任何填充

android - 如何在 Android 的非 Activity 类中访问 getResources()?