Draw bitmap as line on canvas
Vasily Kuragov
Right now, I'm writing my small drawing application, and one of its features is custom brushes from bitmaps. I thought it wouldn't be a big problem that onTouchEvent() calls every action and draws the bitmap on every pixel, but when I swipe quickly, the coordinates slow down and the app draws it as a gap . Does anyone know how to draw lines from point to point using bitmaps?
Cephalosporium
Create an ArrayList here first to save the points/coordinates
ArrayList<PointF> drawPoints=new ArrayList<>();
Then, create this method
public void draw1(float x,float y){
PathMeasure pm=new PathMeasure(path1,false);
float fSegmentLen=pm.getLength()/pm.getLength();
Matrix m=new Matrix();
int ox=-pattern.getWidth()/2;
int oy=-pattern.getHeight()/2;
for (int i=1;i<pm.getLength();i+=increment){
pm.getMatrix(fSegmentLen*i,m,PathMeasure.POSITION_MATRIX_FLAG);
m.preTranslate(ox,oy);
//change pattern below to the bitmap you want to draw
drawCanvas.drawBitmap(pattern,m,drawPaint);
invalidate();
}
}
Then call the above method in onTouchEvent
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX=event.getX();
float touchY=event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
firstPointX=touchX;
firstPointY=touchY;
case MotionEvent.ACTION_MOVE:
drawPoints.add(new PointF(touchX,touchY));
if (drawPoints.size()>=2) {
PointF pointF = drawPoints.get(drawPoints.size()-2);
path1.moveTo(pointF.x, pointF.y);
PointF next = drawPoints.get(drawPoints.size() - 1);
path1.quadTo(pointF.x, pointF.y, next.x, next.y);
//path1.quadTo(firstPointX, firstPointY, next.x, next.y);
draw1(touchX,touchY);
}
invalidate();
path1.reset();
break;
case MotionEvent.ACTION_UP:
drawPoints.clear();
path1.reset();
break;
default:
return false;
}
invalidate();
return true;
}
If you want to use it in Kotlin, you can automatically convert its code to Kotlin in Android Studio, hope it helps, please let me know if it works