2012-04-24 50 views
1

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

我想,虽然做的是让用户也可以选择,如果他们想在小部件圆角。是否有可能动态改变颜色和小部件是否有圆角?从我看过的舍入角的例子看来,您需要知道视图的尺寸,以便您可以在设置位图之前舍入边缘。我不认为这是可能的,从一个小部件,但...任何想法?

回答

4

有这样做的2种方法:

  1. 创建圆角/方角(使用现有的方法)的位图大致是你想要的widget的大小。这有位图扭曲的风险,如果用户调整窗口小部件或使用它的一些屏幕分辨率/ 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); 
    

我使用这两种方法和(2)推荐的最大兼容性。

+0

非常感谢!这正是我正在寻找的... – timothyjc 2012-04-25 10:52:01

+0

嗨!我刚才在这里提出了一个问题http://stackoverflow.com/questions/25877515/appwidget-image-with-rounded-corners,这与这个问题非常相关。任何见解都会很棒! – 2014-09-16 20:07:15

相关问题