3

我有一个带有配置活动的小部件,用户可以在其中从颜色选择器中选择小部件背景的颜色。我正在使用下面的方法,其中我有一个 ImageView 并创建了一个在 ImageView 上动态设置的位图。

http://konsentia.com/2011/03/dynamically-sharing-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));

我想要做的是让用户也选择他们是否想要小部件上的圆角。是否可以动态更改颜色以及小部件是否具有圆角?从我看过的圆角示例中,您似乎需要知道视图的尺寸,以便在设置位图之前可以圆角边缘。我认为这在小部件中是不可能的……有什么想法吗?

4

2 回答 2

10

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

  1. 创建一个圆角/方角的位图(使用您现有的方法),它大致是您想要的小部件的大小。如果用户调整小部件的大小或在具有您未考虑到的某些屏幕分辨率/DPI 的设备上使用它,则存在位图扭曲的风险
  2. Create some white 9 patch bitmap resources with rounded corners and square corners and use RemoteViews.setInt to change the color/transparency of the widget background ImageView (requires Froyo or greater), e.g.

    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);
    

I've used both methods and recommend (2) for maximum compatibility.

于 2012-04-25T09:56:21.273 回答
0

Too late for the answer, but maybe it will be useful to someone. Recently I also figured out how to make rounded corners in RemoteViews. In my case, I needed to display the image by url and make it round cornenrs. Unfortunately, remoteViews.setImageViewResource and remoteViews.setInt didn't work right.

I solved the problem with 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)
于 2021-05-03T07:29:30.267 回答