需求:使TextView中的文字倾斜一定的角度。如下图所示:
如何实现呢?自定义View?这可能是大多数同学产生的第一个想法。的确,自定义View可以实现这个需求。我也找过网上自定义view的方法,大多数只是继承TextView,在onDraw()方法中将画布旋转:
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        canvas.rotate(degrees, this.getWidth() / 2f, this.getHeight() / 2f);
//        canvas.rotate(degrees, 0, 0);
        super.onDraw(canvas);
        canvas.restore();
    }
其中canvas.rotate(degrees, this.getWidth() / 2f, this.getHeight() / 2f);方法中degrees就是需要旋转的角度。
今天介绍一种更简单的方法:
View中有一个属性:rotation,可以实现旋转View。因为TextView是继承的View,所以也可以使用这个属性。
XML中设置
android:rotation="45"
java代码中设置
mTextView.setRotation(45);
View的相关源码:
/**
     * Sets the degrees that the view is rotated around the pivot point. Increasing values
     *设置视图围绕轴心点旋转的度数。
     * result in clockwise rotation.
     *顺时针旋转
     * @param rotation The degrees of rotation.旋转的角度。
     * @see #getRotation()
     * @see #getPivotX()
     * @see #getPivotY()
     * @see #setRotationX(float)
     * @see #setRotationY(float)
     *
     * @attr ref android.R.styleable#View_rotation
     */
    public void setRotation(float rotation) {
        if (rotation != getRotation()) {
            // Double-invalidation is necessary to capture view's old and new areas
            invalidateViewProperty(true, false);
            mRenderNode.setRotation(rotation);
            invalidateViewProperty(false, true);
            invalidateParentIfNeededAndWasQuickRejected();
            notifySubtreeAccessibilityStateChangedIfNeeded();
        }
    }
其实,其他继承View的控件都可以使用这个属性进行旋转。并不影响自身的点击事件。













网友评论