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

tim*_*yjc 1 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

remoteViews.setImageViewBitmap(R.id.bgcolor, getBackground(bgcolor));
Run Code Online (Sandbox Code Playgroud)

我想做的是让用户也选择他们是否想在小部件上使用圆角.是否可以动态更改颜色以及窗口小部件是否具有圆角?从我看过的四舍五入的例子来看,您需要知道视图的尺寸,以便在设置位图之前可以对边缘进行舍入.我不认为这可能来自一个小部件虽然......任何想法?

rof*_*son 5

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

  1. 创建一个圆角/方角(使用现有方法)的位图,大致相当于所需小部件的大小.如果用户调整窗口小部件的大小或在具有某些屏幕分辨率/ DPI的设备上使用它而您没有考虑到,则存在位图扭曲的风险
  2. 使用圆角和方角创建一些白色9补丁位图资源,并使用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);
    
    Run Code Online (Sandbox Code Playgroud)

我已经使用了这两种方法并建议(2)以获得最大的兼容性.