Android对LinearLayout设置圆角及透明背景图片

1.布局文件,图片自己选择

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".transparentActivity">

    <LinearLayout
        android:id="@+id/image"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:orientation="horizontal"
        android:background="@drawable/bg"
        android:alpha="10"
        android:layout_width="400dp"
        android:layout_height="100dp">

    </LinearLayout>


</LinearLayout>

2.编写设置画布的工具类Linear_Image_Radius.java

/**
 * Linear设置圆角背景图片
 */
public class Linear_Image_Radius {
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();

        //创建和原始照片一样大小的矩形
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);//抗锯齿
        canvas.drawARGB(0, 0, 0, 0);

        //paint.setAlpha(1); //这个透明度好像不起作用,可以在主类里再设置
        paint.setColor(color);
        //画一个基于前面创建的矩形大小的圆角矩形
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        //设置相交模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //图片画到矩形
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

3.在Activity内编写setUtils类并调用工具类,给LinearLayout设置背景图片

 private void setUtils(){
        Drawable drawable = getResources().getDrawable(R.drawable.linear_bg);
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        BitmapDrawable bbb = new BitmapDrawable(Linear_Image_Radius.toRoundCorner(bitmap, 120));
        bbb.setAlpha(200); //设置透明度 有效
        LinearLayout image_radius_linear = findViewById(R.id.image_radius_linear);
        image_radius_linear.setBackgroundDrawable(bbb);
    }

设置图片也是同理

ImageView imageView =  findViewById(R.id.imageView);
imageView.setImageBitmap(MyActivity.getRoundedCornerBitmap(bitmap));
imageView.setImageBitmap(MyActivity.toRoundCorner(bitmap, 20));

你可能感兴趣的:(android,android,bitmap,canvas)