TextView中文本倾斜

需求:使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的控件都可以使用这个属性进行旋转。并不影响自身的点击事件。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,018评论 3 119
  • 【Android 动画】 动画分类补间动画(Tween动画)帧动画(Frame 动画)属性动画(Property ...
    Rtia阅读 6,248评论 1 38
  • 每个夜晚,月亮到来,它是那么的静静挂在天空,你只看到它的圆缺,却看不到自己的悲伤。 悲伤从何来,没人打你,没人骂你...
    驭临风阅读 178评论 0 2
  • 暮色染树水涟涟, 晓风残月夜阑珊。 梦里寻君君不见, 隔帘幽雨万重山。
    陈传珍阅读 221评论 0 0
  • 飞舞的蝴蝶 穿过锋利的流言 翅膀不忍再煽动只因雨滴中的暧昧 飞舞的蝴蝶 超越年龄的界限 却冲不过荆棘密布和世俗的枷...
    雨夜拂琴阅读 269评论 2 1