Android provides many drawing actions via paint. It has several features which provide great flexibility. I have needed a feature nowadays, such that a user can draw shapes or lines. At the end of the job, a user should be able to change color of outside part of drawing.
For this picture, the drawing is obvious, its color is black. Filled place is the whole view that contains the drawing but the shape itself and its inside. The code below will result this functionality when used in onDraw() method:
Figure 1 : Example output |
@Override
protected void onDraw(Canvas canvas) {
if(drawings.isEmpty()) {
return;
}
//ArrayList arc = drawings.get(drawings.size()-1);
int height = getMeasuredHeight();
int width = getMeasuredWidth();
Path backpath = new Path();
backpath.moveTo(0, 0);
backpath.lineTo(0, width);
backpath.lineTo(height, width);
backpath.lineTo(height, 0);
backpath.setFillType(Path.FillType.EVEN_ODD);
for(ArrayList arc : drawings) {
Iterator iter = arc.iterator();
Path tempPath = new Path();
PointF p = iter.next();
tempPath.moveTo(p.x, p.y);
while (iter.hasNext()) {
PointF l = iter.next();
tempPath.quadTo(p.x, p.y, l.x, l.y);
p = l;
}
tempPath.lineTo(p.x, p.y);
backpath.addPath(tempPath);
canvas.drawPath(path, mBackgroundPaint);
canvas.drawPath(tempPath, paint);
}
}
Path.FillType.EVEN_ODD does the work here. I have used two paths. First one is for real drawing, tempPath. Second one is to draw background color, backpath.After drawing bounds, I have added a copy of tempPath into backpath. This code block results Figure 1 above.
Comments
Post a Comment