android 自定义LinearLayout 60dp的圆角矩形水印图片
时间: 2023-12-06 21:44:41 浏览: 78
您可以继承LinearLayout类,重写onDraw方法,在该方法中绘制圆角矩形和水印图片。以下是一个示例代码:
```
public class WatermarkLayout extends LinearLayout {
private Paint mPaint;
private Bitmap mWatermarkBitmap;
public WatermarkLayout(Context context) {
super(context);
init();
}
public WatermarkLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public WatermarkLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.parseColor("#80000000")); //设置圆角矩形颜色
mPaint.setAntiAlias(true); //抗锯齿
mPaint.setStyle(Paint.Style.FILL);
mWatermarkBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.watermark); //加载水印图片
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int radius = dp2px(30); //圆角半径
int width = getWidth();
int height = getHeight();
//绘制圆角矩形
RectF rectF = new RectF(0, 0, width, height);
canvas.drawRoundRect(rectF, radius, radius, mPaint);
//绘制水印图片
int watermarkWidth = mWatermarkBitmap.getWidth();
int watermarkHeight = mWatermarkBitmap.getHeight();
int x = (width - watermarkWidth) / 2; //水印图片在LinearLayout中的水平位置
int y = (height - watermarkHeight) / 2; //水印图片在LinearLayout中的垂直位置
canvas.drawBitmap(mWatermarkBitmap, x, y, null);
}
private int dp2px(int dpValue) {
float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
```
使用时,将该自定义布局作为父布局,设置宽高为60dp即可:
```
<com.example.WatermarkLayout
android:layout_width="60dp"
android:layout_height="60dp"
android:gravity="center"
android:orientation="horizontal">
<!-- 子控件 -->
</com.example.WatermarkLayout>
```
阅读全文