Setting GradientDrawable through RemoteView

喜夏-厌秋 提交于 2019-12-01 21:20:51

Tried ImageView as a background (before LinearLayout). It does not provide proper margin to widget. Since the widget text is dynamic, sometimes it goes out of the imageView which is not what I want

I'm not entirely sure what you mean, but if you use a FrameLayout / RelativeLayout for your root layout, and then put the ImageView inside with fill parent, your image should be exactly the size of your widget.

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="6dp" >

    <ImageView
        android:id="@+id/widgetBg"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />

    // Other views

</FrameLayout>

Also, this is what I'm doing to dynamically change the color & alpha of a rounded corner gradient background. Then use setImageViewBitmap( ) to apply to the imageview. Probably there is a better way.

public static Bitmap getBackground(int bgColor, int width, int height, Context context) {
    try {
        // convert to HSV to lighten and darken
        int alpha = Color.alpha(bgColor);
        float[] hsv = new float[3];
        Color.colorToHSV(bgColor, hsv);
        hsv[2] -= .1;
        int darker = Color.HSVToColor(alpha, hsv);
        hsv[2] += .3;
        int lighter = Color.HSVToColor(alpha, hsv);

        // create gradient useng lighter and darker colors
        GradientDrawable gd = new GradientDrawable(
                GradientDrawable.Orientation.LEFT_RIGHT,new int[] { darker, lighter});
        gd.setGradientType(GradientDrawable.RECTANGLE);
        // set corner size
        gd.setCornerRadii(new float[] {4,4,4,4,4,4,4,4});

        // get density to scale bitmap for device
        float dp = context.getResources().getDisplayMetrics().density;

        // create bitmap based on width and height of widget
        Bitmap bitmap = Bitmap.createBitmap(Math.round(width * dp), Math.round(height * dp),
                Bitmap.Config.ARGB_8888);
        Canvas canvas =  new Canvas(bitmap);
        gd.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        gd.draw(canvas);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!