Have you ever said to yourself, ‘Wow, this view needs some stripes, but there is no android:stripes=“true” attribute and I don’t know how to draw stripes using the canvas’? If so, this is the perfect place for you. Or, if you need to draw stripes and figured you’d check the internet for an easy solution before you tried it yourself than you are also in the right place.
For those of you who just want the code here it is.
public class StripedView extends View {
private static final float STRIPE_WIDTH_PERCT = .05f;
private static final float STRIPE_OFFSET_PERCT = .2f;
private Path stripespath = new Path();
private Paint blackPaint = new Paint();
public StripedView(Context context) {
super(context);
}
public StripedView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StripedView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public StripedView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
//init()
{
blackPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawStripes(canvas, 0, getHeight(), 0, getWidth(), blackPaint);
}
private void drawStripes(Canvas canvas, float topy, float bottomy, float startx, float endx, Paint p){
if(bottomy - topy < 1){
return;
}
stripespath.reset();
float width = (bottomy - topy) * STRIPE_WIDTH_PERCT;
float offset = (bottomy - topy) * STRIPE_OFFSET_PERCT;
for(float xPos = startx - offset; xPos <= endx; xPos += offset + width){
stripespath.moveTo(xPos, topy);
stripespath.lineTo(xPos + width, topy);
stripespath.lineTo(xPos + offset + width, bottomy);
stripespath.lineTo(xPos + offset, bottomy);
stripespath.lineTo(xPos, topy);
}
canvas.drawPath(stripespath, p);
}
}
Which will result in something that looks like this.