在Android中使用XML形状设置绘制矩形 [英] Draw rectangle with XML shape settings in Android

查看:692
本文介绍了在Android中使用XML形状设置绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我不知道该如何解决的问题.如果可以,请你帮助我. 在我的应用程序中,我必须创建一个自定义视图扩展视图.在此视图中,我应该绘制很多矩形,并通过canvas.drawRect或canvas.drawRoundRect创建它们.很明显.但是我想为这些矩形(带有渐变,角,填充等)创建复合设计,并且要在XML中进行这些设置(渐变,角,填充等).我该怎么做?问题是我确定XML的形状时只能将此可绘制对象用作背景,但是当我绘制矩形时,无法为矩形设置背景.也许还有另一种解决问题的方法.我可以使用XML形状对象设置背景,设置x,y坐标和宽度,高度的视图对象吗?

I've got a problem which I don't know how to solve. Please, help me if you can. In my app I have to create a custom view extended View. In this view I should draw a lot of rectangles and I create them by canvas.drawRect or canvas.drawRoundRect. It's clear. But I want to create a compound design of these rectangles (with gradients, corners, paddings and etc.) and I want to carry out these settings (gradients, corners, paddings and etc.) in XML. How can I do it? The problem is that I determine shape in XML I can use this drawable only as background but when I draw a rectangle I can't set background for rectangle. Maybe there are another way to solve the problem. Could I use the XML shape object for setting not only as background but a view object with x,y-coordinates and width, height?

我可以画矩形:

canvas.drawRect(x1, y1, x2, y2, paint);

但是我在XML中有这样的矩形设置:

but I have rectangle settings in XML like this:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

<!-- Specify a gradient for the background -->
    <gradient
    android:angle="90"
    android:startColor="#55000066"
    android:centerColor="#FFFFFF"
    android:endColor="#55000066" />

<!-- Specify a dark blue border -->
    <stroke 
    android:width="2dp"
    android:color="#000066" />

<!-- Specify the margins that all content inside the drawable must adhere to -->
    <padding
    android:left="5dp"
    android:right="5dp"
    android:top="5dp"
    android:bottom="5dp" />

<corners
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="10dp" />
</shape>

,我想将此设置应用于我的矩形.怎么样?

and I want to apply this settings to my rectangle. How?

推荐答案

您可以像这样从代码中加载和使用XML定义的drawable:

You can load and use the XML defined drawable from code like so:

public class CustomView extends View {

    Drawable shape;

    public CustomView(Context context) {
        super(context);
        shape = context.getResources().getDrawable(R.drawable.shape);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        shape.setBounds(left, top, right, bottom);
        shape.draw(canvas)
    }

    // ... Additional methods omitted for brevity

}

这篇关于在Android中使用XML形状设置绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆