在画布上绘制Android的最佳方式

时间:2014-04-02 08:53:11

标签: android canvas android-canvas

最好的方法是在画布上绘制下面的图像,使尾部独立于其身体移动

enter image description here

以下是我尝试绘制它的代码:

RectF rectf = new RectF(left, top, right, bottom);                            
path.arcTo(rectf, startAngle, sweepAngle);
path.lineTo(linex, liney);

说明:

我在一个矩形内画一个圆圈。我没画一个完整的圆圈,我从0度到350度开始,然后我从弧线停止的地方画一条线。

图像即将完美。问题在于旋转,当我尝试旋转整个画布旋转但我只希望尾部旋转。

旋转我使用下面的代码:

//This line is being called inside onDraw()
canvas.rotate(rotation, (left+right)/2, (top+bottom)/2);

我基本上是在尝试旋转气泡onTouch事件

View.OnTouchListener touch = new View.OnTouchListener() {


    @Override
    public boolean onTouch(View v, MotionEvent e) {
        if(e.getAction() == MotionEvent.ACTION_MOVE){
            float x = e.getX();
            float y = e.getY();
            updateRotation(x,y);
            invalidate();

        }
        return true;
    }
};


public void updateRotation(float x, float y) {

        double r = Math.atan2(x - (getWidth()/2),  (getHeight()/2) - y);
        rotation = (int) Math.toDegrees(r);

   }

我的完整onDraw()方法如下:

    @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    path.reset();

    left = 50;
    top = 50;
    right = getWidth()- 50;
    bottom = getHeight()-50;
    startAngle = 100;
    sweepAngle = 335;
    linex = (left + right)/2;
    liney = bottom + 50;

    canvas.rotate(rotation, (left+right)/2, (top+bottom)/2);

    RectF rectf = new RectF(left, top, right, bottom);
    path.arcTo(rectf, startAngle, sweepAngle);
    path.lineTo(linex, liney);

    canvas.clipPath(path);
    canvas.drawPath(path, paint);

    canvas.restore();

}

图像旋转前:

enter image description here

旋转后的图像:

enter image description here

1 个答案:

答案 0 :(得分:1)

我花了很多时间在这上面,但它对我的应用程序有用。

我的想法是设定点并画出它,所以你所要做的就是改变linex和liney

你还有什么其他的?

protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    paint.setColor(mContext.getResources().getColor(R.color.black));

    Path path = new Path();
    int left = 50;
    int top = 50;
    int right = getWidth()- 50;
    int bottom = getHeight()-50;
    int linex = getWidth()/2;
    int liney = getHeight();
    int openSize = 20;


    RectF rectf = new RectF(left, top, right, bottom);
    int angle = (int) angle(new Point(getWidth()/2, getHeight()/2), new Point(linex,liney)); 

    int startAngle = angle + (openSize/2);
    int sweepAngle = 360 - openSize;

    path.arcTo(rectf, startAngle, sweepAngle);
    path.lineTo(linex, liney);
    path.close();
    canvas.drawPath(path, paint);

}

private double angle(Point point1, Point point2) {
    double deltaX = (point1.x - point2.x);
    double deltaY = (point1.y - point2.y);
    double angle =  Math.toDegrees(Math.atan2(deltaY, deltaX));
    if (angle < 0) {
        angle += 360;
    }

    if (angle > 360) {
        angle -= 360;
    }
    // Compensate for 0
    angle -= 180;
    return angle;
}