国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android使用ItemDecoration給RecyclerView 添加水印

2019-12-12 03:48:22
字體:
來源:轉載
供稿:網友

前言

項目中有使用到水印效果,如下圖所示。在實現過程中,最終選用ItemDecoration來實現,其中有兩大步驟:自定義Drawable來完成水印圖片、使用ItemDecoration來布局水印。

Demo在 WatermarkFragment 中,效果圖如下:

1. 自定義Drawable完成水印圖片

public class MyDrawable extends Drawable { Paint mPaint; public MyDrawable() {  mPaint = new Paint();  mPaint.setColor(Color.parseColor("#1A000000"));  mPaint.setAntiAlias(true);  mPaint.setTextAlign(Paint.Align.LEFT);//從字的最左邊開始畫  mPaint.setTextSize(54); } @Override public void draw(@NonNull Canvas canvas) {  Rect r = getBounds();  //畫斜著的字  canvas.save();  canvas.rotate(-30, r.left, r.bottom);  canvas.drawText("哈哈哈哈哈哈哈", r.left, r.bottom, mPaint);  canvas.restore(); } /*  復寫這兩個方法是為了當在控件wrap_content時能自己測量出高,同時也方便布局。 */  //傾斜30度,可以算出高來 @Override public int getIntrinsicHeight() {  return (int) (Math.sqrt(3) / 3 * getIntrinsicWidth() + 0.5F); } @Override public int getIntrinsicWidth() {  return (int) (mPaint.measureText("DecorationDraw") + 0.5F); } //...模板方法省略}

這里說一下,自定義該Drawable是比較簡單的,但是想到這一步的話就簡答多了,剛開始是想直接在ItemDecoration里邊繪制邊布局,但后來嘗試了一下太復雜,所以就使用Drawable獨立出來,然后就順利了好多。

2. 使用ItemDecoration布局水印

public class MyDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; private int mScrollY; public MyDecoration() {  mDivider = new MyDrawable(); } @Override public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {  //清除之前畫的  // canvas.drawColor(Color.WHITE);  /*   * 跟著滑動是因為bounds在不停的變化,就是top   */  int top = UIUtil.dp(20) - mScrollY;  // 對于畫多少個水印,根據業務需求來,這里直接畫count個  int itemCount = parent.getAdapter().getItemCount();  // 進行布局  for (int i = 0; i < itemCount; ++i) {   int left = i % 2 == 0 ? UIUtil.dp(20) : parent.getMeasuredWidth() -mDivider.getIntrinsicWidth() - UIUtil.dp(20);   //通過setBounds來控制水印的左右   mDivider.setBounds(left, top, parent.getMeasuredWidth(), top + mDivider.getIntrinsicHeight());   mDivider.draw(canvas);   if (i % 2 == 0) {    top += UIUtil.dp(20) + mDivider.getIntrinsicHeight();   } else {    top += UIUtil.dp(140) + mDivider.getIntrinsicHeight();   }  } } /*  mScrollY用于監測recyclerView的滑動距離,此處使用的是onScrollListener中dy的累加值,當item不發生刪除添加操作時是準確的 */  public void setScrollY(int scrollY) {  this.mScrollY = scrollY; }}

在RecyclerView中:

private int totallyY = 0;recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {  totallyY += dy;  myDecoration.setScrollY(totallyY);  }});

結語

這么寫下來感覺還是很簡單的,剛開始實現時感覺確實有點難度,RecyclerView寫的真的好,藝術般的控件。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 惠安县| 右玉县| 姜堰市| 泰和县| 德清县| 衡阳县| 清苑县| 岑巩县| 平陆县| 商都县| 石景山区| 芜湖市| 麦盖提县| 黑河市| 北辰区| 平江县| 崇义县| 长海县| 温宿县| 同江市| 河北区| 无为县| 寿宁县| 翁源县| 大名县| 商城县| 万山特区| 民和| 玉龙| 鄂尔多斯市| 唐山市| 弥渡县| 江西省| 安泽县| 易门县| 耿马| 盐池县| 洪泽县| 调兵山市| 洪泽县| 湟源县|