Android 怎麼畫頂部帶鋸齒的長方形

最近項目中需要一個長方形頂部帶鋸齒的需求,如果用切圖片的話要切好幾套圖,增加apk的大小,而且android手機尺寸眾多,屏幕一大就容易把圖片拉伸,圖片失真也不好,於是就手動畫一個,先看一下動圖。

接下來就是怎麼重寫view,在寫之前先來認識一下幾個方法moveTo(float x, float y) , lineTo(float x, float y) ,addArc(RectF oval, float startAngle, float sweepAngle),為什麼要說,因為下面要用,

/** * Set the beginning of the next contour to the point (x,y). *

Advertisements

* @param x The x-coordinate of the start of a new contour

* @param y The y-coordinate of the start of a new contour */

public void moveTo(float x, float y) {

native_moveTo(mNativePath, x, y);

}

源碼的大致意思就是:畫下一圖形的起始點。沒有繪製,看不到效果。

其實我的英語水平很low,不過簡單一點的還是能看懂,希望沒有誤導大家,哈哈。

/** * Add a line from the last point to the specified point (x,y).

Advertisements

* If no moveTo() call has been made for this contour, the first point is

* automatically set to (0,0). *

* @param x The x-coordinate of the end of a line

* @param y The y-coordinate of the end of a line

*/

public void lineTo(float x, float y) {

isSimplePath = false;

native_lineTo(mNativePath, x, y);

}

大致意思是:從最後一個點到指定的點畫一條線,如果沒有設置moveTo(),畫的起始點就是(0,0)。這個是有繪製的,可以看見。

/** * Add the specified arc to the path as a new contour. *

* @param oval The bounds of oval defining the shape and size of the arc

* @param startAngle Starting angle (in degrees) where the arc begins

* @param sweepAngle Sweep angle (in degrees) measured clockwise

*/

public void addArc(RectF oval, float startAngle, float sweepAngle) {

addArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle);

}

大致意思:給path添加一個指定的弧

要畫的圖形如下:

下面我的思路,網上各種作圖軟體麻煩,於是就自己手動畫了一張圖,字丑勿怪,如圖:

把鋸齒分割中半圓和頂部的長方形,這樣for循環就可以橫向畫鋸齒了,

全部代碼

public class SawtoothView extends View {

private int size = 36;

private int width = 20;

private Paint paint = new Paint();

public SawtoothView(Context context, AttributeSet attrs) {

super(context, attrs);

paint.setColor(getResources().getColor(R.color.colorAccent)); //消除鋸齒

paint.setAntiAlias(true);

paint.setStrokeWidth(0);

paint.clearShadowLayer(); //設置鏤空(方便查看效果)

paint.setStyle(Paint.Style.FILL);

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

int halfHeight = getHeight() >> 1;// 相當於num除以2 此處裝逼請忽略

for (int i = 0; i <= getWidth(); i += size) {

int j = i/size;

Path path = new Path();

path.moveTo(j*(size+width), halfHeight);

path.addArc(new RectF(j*(size+width), (getHeight() - 20) / 2, j*(size+width)+size, (getHeight() + 20) / 2), 0, 180);

path.moveTo((j+1)*size+j*width, halfHeight);

path.lineTo((j+1)*(width+size), halfHeight);

path.lineTo((j+1)*(width+size), 0);

path.lineTo(j*(width+size), 0);

path.lineTo(j*(width+size), halfHeight);

canvas.drawPath(path, paint);

}

}

}

效果圖看下:

最後附上demo地址:

https://github.com/xuetenglong/SawtoothView

Advertisements

你可能會喜歡