• UI设计篇·入门篇·绘制简单自定义矩形图/设置按钮按下弹起颜色变化/设置图形旋转


    Android的基本控件和图形有限,难以满足所有的实际需要和设计需求,好在Android给出了相对完善的图形绘制和自定义控件的API,利用这些API,可以基本满足设计的需求。

    自定义图像和控件的方法:

    1.自定义一个class,继承View,给出含有context和context,attr两种参数的构造方法,在构造方法中设置相关的需求

    2.在Layout设计窗口,通过包名+自定义class类名来调用此视图,并可以跟系统控件设置完全相同

    一个简单自定义视图的的类代码:

    //自定义一个简单的矩形视图

    public
    class MyRect extends View { public MyRect(Context context) { super(context); } public MyRect(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundColor(Color.BLACK);      //设置该矩形的背景为黑色 } }

    调用的Layout XMl文档代码:

    <andrew.com.custompaintdemo.MyRect
      android:layout_width="100dp"
       android:layout_height="100dp" />


    二、为按钮设置点击的颜色变化

    在Drawable文件夹下新建一个XML文档,用来声明按钮点击变化选项:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="false" android:drawable="@color/colorAccent"></item>    //没按下的颜色
        <item android:state_pressed="true" android:drawable="@color/colorPrimary"></item>    //按下后的颜色
    </selector>

    具体的使用代码:

    <Button
      android:text
    ="Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/buttonskin"    //此处即为设置按钮颜色变化的代码引用语句
    />


    三、设计一个不断旋转的矩形图像步骤:

    1.自定义class并继承View,重写相关方法

    2.包名+类名引用

    public class RotatingRect extends View {
        public RotatingRect(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initproperties();        //这是包含了画笔初始方法,每个构造方法都调用,保证一定能够初始化
        }
    
        public RotatingRect(Context context, AttributeSet attrs) {
            super(context, attrs);
            initproperties();
        }
    
        public RotatingRect(Context context) {
            super(context);
            initproperties();
        }
    
        private void initproperties(){
            paint = new Paint();
    
            paint.setColor(Color.RED);
        }
    
        @Override
        public void draw(Canvas canvas) {            //重写draw方法,自行设置绘制代码
            super.draw(canvas);
            canvas.save();                     //保存绘制信息
            canvas.rotate(degrees,100,100);           //旋转一定的角度
            canvas.drawRect(0,0,100,100,paint);         //绘制一个矩形,并传入画笔工具
            degrees++;                        //每一次绘制后,旋转的角度+1
            canvas.restore();                    
    
            invalidate();           //注:一直重绘,很耗资源,但延时难以获得连续的变化效果
        }
    
        private Paint paint;  
        private float degrees;      //这是每次变化的角度
    }
  • 相关阅读:
    centos7的网络设置
    day1学习
    举例讲解Linux系统下Python调用系统Shell的方法
    Python引用模块和查找模块路径
    详解Python中的循环语句的用法
    [cf1566H]Xorquiz
    [luogu5180]支配树
    [atAGC055D]ABC Ultimatum
    [cf1552H]A Serious Referee
    [gym102538H]Horrible Cycles
  • 原文地址:https://www.cnblogs.com/thinfog/p/5710753.html
Copyright © 2020-2023  润新知