Android 绘制rotate控件/图像

本文介绍了一种自定义的Android视图组件RotatelView,该组件可通过setOrientation方法实现平滑旋转效果。通过控制旋转角度及动画效果,使得视图能够在不同角度间平稳过渡。

       参数degree是手机旋转的角度,通过系统方法可得到;animation是否需要动画。该View作为一个控件使用,需要在程序中通过调用setOrientation()方法,来使其产生作用。

<span style="font-family:Arial;font-size:18px;"><span style="font-size:18px;"> public class RotatelView extends View    {

    private static final int ANIMATION_SPEED = 270;
    private int mCurrentDegree = 0; // [0, 359]
    private int mStartDegree = 0;
    private int mTargetDegree = 0;
    private boolean mClockwise = false;
    private boolean mEnableAnimation = true;
    private long mAnimationStartTime = 0;
    private long mAnimationEndTime = 0;

    public void setOrientation(int degree, boolean animation) {
        mEnableAnimation = animation;
        // make sure in the range of [0, 359]
        degree = degree >= 0 ? degree % 360 : degree % 360 + 360;
        if (degree == mTargetDegree)
            return;

        mTargetDegree = degree;
        if (mEnableAnimation) {
            mStartDegree = mCurrentDegree;
            mAnimationStartTime = AnimationUtils.currentAnimationTimeMillis();

            int diff = mTargetDegree - mCurrentDegree;
            diff = diff >= 0 ? diff : 360 + diff; // make it in range [0, 359]

            // Make it in range [-179, 180]. That's the shorted distance between the
            // two angles
            diff = diff > 180 ? diff - 360 : diff;

            mClockwise = diff >= 0;
            mAnimationEndTime = mAnimationStartTime
                    + Math.abs(diff) * 1000 / ANIMATION_SPEED;
        } else {
            mCurrentDegree = mTargetDegree;
        }
        invalidate();
    }

 @Override
    protected void onDraw(Canvas canvas) {

        if (mCurrentDegree != mTargetDegree) {
            long time = AnimationUtils.currentAnimationTimeMillis();
            if (time < mAnimationEndTime) {
                int deltaTime = (int) (time - mAnimationStartTime);
                int degree = mStartDegree + ANIMATION_SPEED
                        * (mClockwise ? deltaTime : -deltaTime) / 1000;
                degree = degree >= 0 ? degree % 360 : degree % 360 + 360;
                mCurrentDegree = degree;
                invalidate();
            } else {
                mCurrentDegree = mTargetDegree;
            }
        }       
        canvas.rotate((float) -mCurrentDegree);
        super.onDraw(canvas);
    }
}

来源:修改相机中的缩放图,使其能够平滑旋转。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值