android - 扩展 LinearLayout 不旋转

标签 android layout rotation

我正在尝试创建一个自定义 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/

相关文章:

css - 提高 css3 文本旋转质量

java - 为什么我的应用程序会因为 ImageView 而崩溃?

android - onCreate 流程在完成()之后继续

android - Adobe AIR 移动应用程序 (iOS/Android) 的空闲计时器

multithreading - 线程内存布局

java - 如何将 ImageView 移至顶部?

android - 在 Android 操作系统上运行 Haskell 程序

android - 如何用空字符串消除 textview 的边距?

css - 为什么在Webkit中旋转元素时html子元素消失?

c++ - 在 3D 世界中移动 - OpenGL