在小部件中动态设置ImageView的圆角?

时间:2012-04-24 22:39:08

标签: android widget imageview

我有一个带有配置活动的小部件,用户可以从颜色选择器中选择小部件背景的颜色。我使用下面的方法,我有一个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 个答案:

答案 0 :(得分:5)

有两种方法可以做到这一点:

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

    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);
    
  3. 我已经使用了这两种方法并建议(2)以获得最大的兼容性。

答案 1 :(得分: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)