绘制一个形状,并在用户触摸时使其变大



我看过如何在Android中绘制形状,但我想知道的是当用户触摸形状时如何重新缩放形状。

想象一下,屏幕角落里有一个正方形,当你触摸它时,它会一直长到适合整个屏幕。我想做一个过渡,动画,而不是即时。

知道如何做到这一点吗,或者有任何已知的资源吗?

Android内置了对动画的支持。在网上搜索可以找到许多例子。这是一个良好的开端。

为了使形状可触摸,您可以通过重写View类来实现它们(这里有一个很好的例子)。然后您可以使用View.OnTouchListener.

内置动画在Android中很好,但无论如何都不是最高效的。如果性能是必须的,我建议您创建自己的方法。我要做的是创建一个扩展View的类,并给它一个边界框(Rect/RectF)和一个圆。然后,您可以使用边界框来检测圆何时被触摸。

public class Circle extends View {
    public static final float SCALE_AMOUNT = 1.0f;
    public RectF boundingBox;
    private Paint paint;
    private float circleCenterX, circleCenterY, circleRadius;
    private float x, y;
    public Circle(Context context) {
        super(context);
        // Create paint
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        // Set circle start radius
        circleRadius = 50.0f;
        // Set start x and y (this is the upper left hand corner)
        x = 100.0f;
        y = 100.0f;
        // Create boundingBox
        boundingBox = new RectF();
        boundingBox.left = x;
        boundingBox.top = y;
        boundingBox.right = x + (circleRadius*2);
        boundingBox.bottom = y + (circleRadius*2);
        // Set circleCenterX and circleCenterY (the center of the bounding box and circle)
        circleCenterX = x + circleRadius;
        circleCenterY = y + circleRadius;
    }
    public void scale(boolean scaleUp) {
        float scaleBy = (scaleUp) ? SCALE_AMOUNT : -SCALE_AMOUNT;
        // Update circleRadius
        circleRadius += scaleBy;
        // Update the bounding box
        boundingBox.left = x;
        boundingBox.top = y;
        boundingBox.right = x + (circleRadius*2);
        boundingBox.bottom = y + (circleRadius*2);
        // Update the circle center positions
        circleCenterX = x + circleRadius;
        circleCenterY = y + circleRadius;
    }
    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawCircle(circleCenterX, circleCenterY, circleRadius, paint);
    }
}

然后在Activity类中覆盖onTouchEvent()方法,并检查您的Circle是否被触摸。

Circle circle = new Circle(this);
@Override
public void onDraw(Canvas canvas) {
    circle.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction();
    float x = event.getX();
    float y = event.getY();
    // Detect if pointer goes down on screen
    if(action == MotionEvent.ACTION_DOWN) {
        if(circle.boundingBox.contains(x, y) == true) {
            // Circle was touched so scale it
            circle.scale(true); // true is scale up, false is scale down
        }
    }
    return true;
}

这会在你每次触摸圆形/矩形时缩放它。如果你想让它不断增长,你可以有一个布尔变量,当你触摸形状时,它会设置为true,并一直增长到你拿起手指。我还没有尝试过这个代码,只是很快就输入了它,所以它可能不会编译,但这将是你最好的选择。添加许多形状并检测所有形状上的触摸真的很容易。为每个添加不同的效果。。。等等。我不想为你做所有的事情,但这应该为你指明正确的方向。

也许这个github项目可以帮助您:https://github.com/markushi/android-circlebutton

最新更新