我正在尝试创建一个自定义 LinearLayout
,它可以将布局中的所有子元素旋转一个设定的角度。也就是说,我想旋转整个 Canvas 和 child ,而不是单独的 child 。
我需要支持 API Level 10
,所以 API Level 11
中引入的 android:rotate
在这里对我没有帮助。
我一直在环顾四周,认为我需要按照下面这段代码的行做一些事情,但是使用这段代码没有任何旋转。
关于我在这里遗漏了什么有什么想法吗?
public class RotationLayout extends LinearLayout {
public RotationLayout(Context context) {
super(context);
init();
}
public RotationLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RotationLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(350,0,0);
super.onDraw(canvas);
canvas.restore();
}
}`
最佳答案
我尝试了您的代码并做了一些更改。
在 Activity 类的 onCreate(Bundle) 中,我初始化了 RotationLayout:
RotationLayout rl = new RotationLayout(this);
ImageView iv = new ImageView(this);
iv.setImageDrawable(getResources().getDrawable(R.drawable.some_drawable));
rl.addView(iv);
setContentView(rl);
并且 View 确实围绕 (0,0) 旋转了 350 度(或逆时针旋转 10 度)。这是我改变的:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.rotate(350,0,0);
}
来自关于 Canvas.save()
的注释 (Link) :
Saves the current matrix and clip onto a private stack. Subsequent calls to translate,scale,rotate,skew,concat or clipRect,clipPath will all operate as usual, but when the balancing call to restore() is made, those calls will be forgotten, and the settings that existed before the save() will be reinstated.
关于android - 扩展 LinearLayout 不旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013825/