Android 长方形色盘
时间: 2023-11-22 13:48:22 浏览: 77
以下是一个Android长方形色盘的实现方法:
1.在res/drawable文件夹下创建一个selector.xml文件,代码如下:
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFD2D2" />
<corners android:radius="1dp"/>
<gradient android:angle="0" android:startColor="#FF3333" android:endColor="#F8F8F8" android:type="linear" />
</shape>
</item>
</selector>
```
2.在布局文件中添加自定义的RectangleColorSelectorView,代码如下:
```xml
<com.example.colorselfdefinedemo.RectangleColorSelectorView
android:id="@+id/self_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
```
3.创建RectangleColorSelectorView类并继承View类,代码如下:
```java
public class RectangleColorSelectorView extends View {
private Paint mPaint;
private int mWidth;
private int mHeight;
public RectangleColorSelectorView(Context context) {
super(context);
init();
}
public RectangleColorSelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RectangleColorSelectorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mWidth = getWidth();
mHeight = getHeight();
LinearGradient linearGradient = new LinearGradient(0, 0, mWidth, 0, new int[]{Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA, Color.RED}, null, Shader.TileMode.CLAMP);
mPaint.setShader(linearGradient);
canvas.drawRect(0, 0, mWidth, mHeight, mPaint);
}
}
```
阅读全文