2012-04-24 88 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