SurfaceView實現圓角矩形預覽
阿新 • • 發佈:2019-01-22
android中,文字、按鈕實現圓角樣式只需要在其背景中定義corners屬性設定radius即可。
在SurfaceView中同樣可以實現此種效果,以豐富預覽樣式。
比如用SurfaceView要實現圓角矩形預覽的效果,自定義View繼承於SurfaceView,然後重寫其draw方法,這點不同於ImageView實現圓角效果,ImageView要重寫其onDraw方法。具體程式碼,如下。
@Override public 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實現圓角程式碼@Override protected 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); }
備註:如上的寫法只能適配部分機型,更全面的適配參考點我圓角dialog的寫法 20180809