可选择的圆形ImageView的如Google +可选择、圆形、Google、ImageView

2023-09-05 03:36:25 作者:奢侈的爱情

如何创建一个可选择的圆形的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.

我尝试复制的资料图片1到1。

I try to replicate the profile pictures 1 to 1.

我的工作至今:

loadedImage 位图其中显示

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

在使用的方法:

The used methods:

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.

位图尺寸: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;
}