自定义View

流程:
  • 创建MyView继承View/ViewGroup,需要三个构造方法
  • 重写onDraw()方法
  • 在布局xml中引用
如果需要添加自定义view的自定义属性:
  • 在values包下的attrs文件中添加属性id
  • 在 MyView的构造方法中解析这个属性值, 在onDraw()中设置这个值
  • 在布局xml中引用

自定义View需要注意的坑

  • 支持特殊属性,warp_content,padding & margin
    如果不在onMeasur()中设置warp_content属性,那么设置wrap_content则会失效,至于为什么以后再补吧
  • 多线程直接使用post(),view本生提供了post,不需要自己创建handler
  • 注意内存泄漏,动画需要及时停止
  • 处理好事件冲突

demo:

创建MyView,继承View/ViewGroup

public class CircularCoverView extends View

在values下的attrs文件创建CircularCoverView的自定义属性


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--RoundImageView-->
    <declare-styleable name="roundedimageview">
        <attr name="border_thickness" format="dimension" />
        <attr name="border_inside_color" format="color" />
        <attr name="border_outside_color" format="color"/>
        <attr name="border_radius" format="dimension"/>
    </declare-styleable>
</resources>

重写三个构造方法,在构造方法中解析自定义属性

 public CircularCoverView(Context context) {
        this(context, null, 0);
    }

    public CircularCoverView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircularCoverView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircularCoverView);
        leftTopRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_left_top_radius, leftTopRadians);
        leftBottomRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_left_bottom_radius, leftBottomRadians);
        rightTopRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_right_top_radius, rightTopRadians);
        rightBottomRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_right_bottom_radius, rightBottomRadians);
        coverColor = typedArray.getColor(R.styleable.CircularCoverView_cover_color, coverColor);
    }

重写onDraw()

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        try {
            Paint paint = new Paint();
            paint.setFilterBitmap(false);
            paint.setStyle(Paint.Style.FILL);
            //create a canvas layer to show the mix-result
            @SuppressLint("WrongConstant") int sc = canvas.saveLayer(0, 0, getWidth(), getHeight(), null);
            //draw sector-dst-bitmap at first.
            canvas.drawBitmap(drawSector(getWidth(), getHeight()), 0, 0, paint);
            //set Xfermode of paint.
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
            //then draw rect-src-bitmap
            canvas.drawBitmap(drawRect(getWidth(), getHeight()), 0, 0, paint);
            paint.setXfermode(null);
            //restore the canvas
            canvas.restoreToCount(sc);
        }catch (Error e){

        }
    }

在xml引用并且设置自定义属性值

<com.jszc.mobile.videostream.ui.CircularCoverView
            android:id="@+id/head_cover"
            android:layout_width="56dp"
            android:layout_height="56dp"
            android:layout_centerInParent="true"
            app:left_top_radius="28dp"/>

完整的代码


public class CircularCoverView extends View {

  private int leftTopRadians = 30;        //leftTopRadians
  private int leftBottomRadians = 30;     //leftBottomRadians
  private int rightTopRadians = 30;       //rightTopRadians
  private int rightBottomRadians = 30;    //rightBottomRadians
  private int border = 0;

  private int coverColor = 0xffeaeaea;    //color of cover.

  public CircularCoverView(Context context) {
      this(context, null, 0);
  }

  public CircularCoverView(Context context, AttributeSet attrs) {
      this(context, attrs, 0);
  }

  public CircularCoverView(Context context, AttributeSet attrs, int defStyleAttr) {
      super(context, attrs, defStyleAttr);
      TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircularCoverView);
      leftTopRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_left_top_radius, leftTopRadians);
      leftBottomRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_left_bottom_radius, leftBottomRadians);
      rightTopRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_right_top_radius, rightTopRadians);
      rightBottomRadians = typedArray.getDimensionPixelSize(R.styleable.CircularCoverView_right_bottom_radius, rightBottomRadians);
      coverColor = typedArray.getColor(R.styleable.CircularCoverView_cover_color, coverColor);
  }


  /**
   * set radians of cover.
   */
  public void setRadians(int leftTopRadians, int rightTopRadians, int leftBottomRadians, int rightBottomRadians,int border) {
      this.leftTopRadians = leftTopRadians;
      this.rightTopRadians = rightTopRadians;
      this.leftBottomRadians = leftBottomRadians;
      this.rightBottomRadians = rightBottomRadians;
      this.border = border;
  }

  /**
   * set color of cover.
   *
   * @param coverColor cover's color
   */
  public void setCoverColor(@ColorInt int coverColor) {
      this.coverColor = coverColor;
  }

  /**
   * create a sector-bitmap as the dst.
   *
   * @param w width of bitmap
   * @param h height of bitmap
   * @return bitmap
   */
  private Bitmap drawSector(int w, int h) {
      Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
      Canvas c = new Canvas(bm);
      Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
      p.setColor(0xFFFFCC44);//notice:cannot set transparent color here.otherwise cannot clip at final.

      c.drawArc(new RectF(border, border, leftTopRadians * 2+border, leftTopRadians * 2+border), 180, 90, true, p);
      c.drawArc(new RectF(border, getHeight() - leftBottomRadians * 2-border, leftBottomRadians * 2+border, getHeight()-border), 90, 90, true, p);
      c.drawArc(new RectF(getWidth() - rightTopRadians * 2-border, border, getWidth()-border, rightTopRadians * 2+border), 270, 90, true, p);
      c.drawArc(new RectF(getWidth() - rightBottomRadians * 2-border, getHeight() - rightBottomRadians * 2-border, getWidth()-border, getHeight()-border), 0, 90, true, p);
      return bm;
  }

  /**
   * create a rect-bitmap as the src.
   *
   * @param w width of bitmap
   * @param h height of bitmap
   * @return bitmap
   */
  private Bitmap drawRect(int w, int h) {
      Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
      Canvas c = new Canvas(bm);
      Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
      p.setColor(coverColor);

      c.drawRect(new RectF(border, border, leftTopRadians+border, leftTopRadians+border), p);
      c.drawRect(new RectF(border, getHeight() - leftBottomRadians-border, leftBottomRadians+border, getHeight()-border), p);
      c.drawRect(new RectF(getWidth() - rightTopRadians-border, border, getWidth()-border, rightTopRadians+border), p);
      c.drawRect(new RectF(getWidth() - rightBottomRadians-border, getHeight() - rightBottomRadians-border, getWidth()-border, getHeight()-border), p);

      c.drawRect(new RectF(0, 0, getWidth(), border), p);
      c.drawRect(new RectF(0, 0, border, getHeight()), p);
      c.drawRect(new RectF(getWidth()-border, 0, getWidth(), getHeight()), p);
      c.drawRect(new RectF(0, getHeight()-border, getWidth(), getHeight()), p);

      return bm;
  }

  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  @Override
  protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      try {
          Paint paint = new Paint();
          paint.setFilterBitmap(false);
          paint.setStyle(Paint.Style.FILL);

          //create a canvas layer to show the mix-result
          @SuppressLint("WrongConstant") int sc = canvas.saveLayer(0, 0, getWidth(), getHeight(), null);
          //draw sector-dst-bitmap at first.
          canvas.drawBitmap(drawSector(getWidth(), getHeight()), 0, 0, paint);
          //set Xfermode of paint.
          paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
          //then draw rect-src-bitmap
          canvas.drawBitmap(drawRect(getWidth(), getHeight()), 0, 0, paint);
          paint.setXfermode(null);
          //restore the canvas
          canvas.restoreToCount(sc);
      }catch (Error e){

      }
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容