小部件中动态设置的ImageView如何实现圆角?

4
我有一个小部件,其中包含一个配置活动。在这个活动中,用户可以从颜色选择器中选择小部件背景的颜色。我使用下面的方法:我有一个 ImageView,并创建了一个位图,我将其动态地设置在 ImageView 上。
参考链接:http://konsentia.com/2011/03/dynamically-changing-the-background-color-in-android-widgets/
public static Bitmap getBackground (int bgcolor)
{
try
    {
        Bitmap.Config config = Bitmap.Config.ARGB_8888; // Bitmap.Config.ARGB_8888 Bitmap.Config.ARGB_4444 to be used as these two config constant supports transparency
        Bitmap bitmap = Bitmap.createBitmap(2, 2, config); // Create a Bitmap

        Canvas canvas =  new Canvas(bitmap); // Load the Bitmap to the Canvas
        canvas.drawColor(bgcolor); //Set the color

        return bitmap;
    }
    catch (Exception e)
    {
        return null;
    }
}

那么

remoteViews.setImageViewBitmap(R.id.bgcolor, getBackground(bgcolor));

然而,我希望用户也能选择小部件是否要有圆角。是否可以动态更改小部件的颜色和是否有圆角?从我查看的圆角示例中,似乎需要知道视图的尺寸才能在设置位图之前对边缘进行处理。但我不认为这在小部件内是可能的...有什么想法吗?

2个回答

12

有两种方法可以实现这个:

  1. 创建一个带有圆角/方角的位图(使用现有方法),大小大致与所需小部件相同。这种方法存在风险,如果用户调整小部件的大小或在使用您未考虑屏幕分辨率/DPI的设备上使用它,则可能会导致位图变形。
  2. 创建一些带有圆角和方角的白色9 patch位图资源,并使用RemoteViews.setInt更改小部件背景ImageView的颜色/透明度(需要Froyo或更高版本),例如:

  3. if(roundCorners)
        remoteViews.setImageViewResource(R.id.widget_background, R.drawable.round_corners);
    else
        remoteViews.setImageViewResource(R.id.widget_background, R.drawable.square_corners);  
    
    remoteViews.setInt(R.id.widget_background, "setColorFilter", someColor);
    remoteViews.setInt(R.id.widget_background, "setAlpha", someAlphaLevel);
    

    我两种方法都用过,建议使用(2)以获得最大的兼容性。


嗨!我刚在http://stackoverflow.com/questions/25877515/appwidget-image-with-rounded-corners这里提了一个问题,与这个问题非常相关。任何见解都将是极好的! - Will Thomson

0

回答有点晚,但也许对某些人有用。最近我也找到了如何在RemoteViews中制作圆角的方法。

在我的情况下,我需要通过URL显示图像并使其成为圆形角。不幸的是,remoteViews.setImageViewResourceremoteViews.setInt没有正常工作。

我使用Glide解决了这个问题:

val notificationTarget = NotificationTarget(
    baseContext,
    R.id.id_of_your_image_view,
    expandedView,
    notification,
    NOTIFICATION_ID
)
Glide.with(baseContext.applicationContext)
    .asBitmap()
    .load("url of the image")
    .circleCrop() // the method that rounds the corners
    .into(notificationTarget)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接