【问题标题】:How to get canvas of separate View如何获取单独视图的画布
【发布时间】:2014-05-03 06:01:54
【问题描述】:

我想在布局中使用一些自定义视图,如图所示。

红色矩形,它只是视图的边框。里面可能有不同的东西。

为此我创建了自定义视图:

公共类 CustomView 扩展视图 {

public CustomView(Context context) {
    super(context);
}

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawCircle(5, 5, 5, paint);
    canvas.save();
}

}

然后在 onCreate() 方法的某个地方,我向布局添加了一些视图:

layout.addView(new CustomView(this));
layout.addView(new CustomView(this));

结果圆形被绘制在布局的左上角(图片上的黑色矩形)。

我认为 onDraw() 方法包含单独视图的画布。

如何在单独的视图范围内而不是在所有布局范围内绘制一些东西?

【问题讨论】:

    标签: android canvas view


    【解决方案1】:

    您可以在 xml 中执行此操作。您可以创建一个可绘制资源(称为 red_border.xml)...

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <shape android:shape="rectangle">
                <stroke android:width="1dp" android:color="@android:color/holo_red_light"/>
                <size android:width="25dp" android:height="25dp"/>
            </shape>
        </item>
    </selector>
    

    并将其分配给特定视图。

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/red_border">
    </LinearLayout>
    

    这将适用于更多视图,而不仅仅是布局(TextView、EditText 等...)。

    希望这会有所帮助。

    【讨论】:

    • 刚刚意识到您可能一直在谈论如何使用画布做到这一点。但这应该能给你想要的样子。
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多