如何在画布上绘制不受缩放影响的圆圈

时间:2015-11-05 06:06:46

标签: android android-canvas android-custom-view

有人知道如何修改圆的半径,尽管缩放同一画布中的其他东西。我真的不知道如何动态获得圆的比例因子。感谢

    Canvas c = new Canvas(image); 
    c.drawColor(Color.TRANSPARENT, Mode.CLEAR);
    c.drawBitmap(bm, 0, 0, null); 
    c.drawCircle(cx, cy, radius, mPaint); 

Canvas c = new Canvas(image); //这个图像有一个矩阵,每当我在图像上缩放时,光标也会改变。我希望光标大小保持为13.0f。

代码:

public void draw(Canvas canvas, Paint paint) { //This is access from the main onDraw();
    paint.setColorFilter(colorFilter);
   // scaled bitmap base on the scaling of the bitmap
    canvas.drawBitmap(bitmap, matrix, paint);
    if(activateCursor == true){
        if(isTouched == true && ActivityMainEditor.IS_ERASING == true){
            RectF r = new RectF(); 
            matrix.mapRect(r);

            // sol1
            float scaledX = (lastX - r.left) + 48;
            float scaledY = (lastY - r.top) - 137;
            float[] values = new float[9];
            matrix.getValues(values);

            // mScalingFactor shall contain the scale/zoom factor
            float scalex = values[Matrix.MSCALE_X];
            float skewy = values[Matrix.MSKEW_Y];
            float scale = (float) Math.sqrt(scalex * scalex + skewy * skewy);
            scaledX /= scale;
            scaledY /= scale;
            // cursor adjustment

虽然缩放了位图,但我已经使用这些线来使圆半径始终相同,但是当缩放时它不准确但是当缩放时,光标也会变得更大。

            float scaleCursor = (float) Math.sqrt((scalex - 5) * (scalex - 5) + (skewy - 2) * (skewy - 2));
            float cursorSize = (13.0f / scaleCursor); // 13.0f fixed circle radius

            drawACircle(canvas, bitmap, scaledX, scaledY, cursorSize);  
        }
    }

}

private Bitmap drawACircle(Canvas c, Bitmap bm, float cx, float cy, float radius)
{
    Bitmap bmOverlay = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas cd = new Canvas(bmOverlay); 
    cd.drawColor(Color.TRANSPARENT, Mode.CLEAR);
    cd.drawBitmap(bm, 0, 0, null);
 // the line in which the circle will also get scaled :(
    cd.drawCircle(cx, cy, radius, mPaint);
 // update the main bitmap
    bitmap = bmOverlay;
    if(saveNow == true){
        imageHistory.add(bitmap);
        saveNow = false;
    }
    return bmOverlay;
}

1 个答案:

答案 0 :(得分:3)

很简单:

c.scale(x,y); // scales the whole canvas (preconcat the matrix with the scale factor)
c.save(); // saves this matrix
// Do all your drawing here except the `drawCircle`.
c.restore(); // restores the original matrix
c.drawCircle(cx, cy, radius, mPaint); 

致电restore()后,矩阵将返回原始矩阵。您现在可以以正常方式绘制圆圈。

<强>更新
xy设置为CustomView中的字段,这样您就可以在onDraw方法之外修改它们。因此,在onTouchonTouchEvent中,您可以修改xy并致电invalidate()。这将调用onDraw,此处将进行缩放。这将为您提供所需的信息。在全局缩放的情况下,始终使用canvas.scale()而不是缩放单个绘制元素。这将使事情变得简单。