SurfaceView实现圆角矩形预览

来源:互联网 发布:手机淘宝取消不了退款 编辑:程序博客网 时间:2024/05/17 07:45
android中,文本、按钮实现圆角样式只需要在其背景中定义corners属性设置radius即可。
在SurfaceView中同样可以实现此种效果,以丰富预览样式。
比如用SurfaceView要实现圆角矩形预览的效果,自定义View继承于SurfaceView,然后重写其draw方法,这点不同于ImageView实现圆角效果,ImageView要重写其onDraw方法。具体代码,如下。
@Overridepublic void draw(Canvas canvas) {    Path path = new Path();              //用矩形表示SurfaceView宽高    RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());            //15.0f即是圆角半径           path.addRoundRect(rect, 15.0f, 15.0f, Path.Direction.CCW);    //裁剪画布,并设置其填充方式      canvas.clipPath(path, Region.Op.REPLACE);      super.draw(canvas); }
同理,要实现其他样式的效果,只需要调用Canvas类中的其他画图方法就好。
不过,要想实现预览,还需要在布局中加入背景,一般设置为透明色就好了。
最后,上图展示实现效果。
附:ImageView实现圆角代码
        @Overrideprotected void onDraw(Canvas canvas) {Path clipPath = new Path();int w = this.getWidth();int h = this.getHeight();clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);canvas.clipPath(clipPath);super.onDraw(canvas);}



0 0