android 文字倾斜,TextView中文本倾斜

需求:使TextView中的文字倾斜一定的角度。如下图所示:

708fd614c4f0

如何实现呢?自定义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的控件都可以使用这个属性进行旋转。并不影响自身的点击事件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值