本文主要是介绍仿太极图自定义view,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前因
鉴于各种原因,一致认为一个优雅的程序猿是从开始写博客成长起来的,虽然我很菜,但我有自知之明啊~~~公司项目最近两天即将上线,所以最近有点时间去整理下最近几天的收货,今天写了一个自定义view,一个很简单很简单的view,而且是一个然并卵的view~~~~
Github: https://github.com/icuihai
微博 : http://weibo.com/icuihai
邮箱: icuihai@aliyun.com;
后果
1,自定义view呢一般分为三种,一是继承现有控件,可以增加其功能,二是组合控件,比如说我们可以让一个组合空间既能有textview的效果,又有togglebutton的效果,第三种则是用的比较多,稍微有点复杂的继承view或者viewgroup容器实现手绘控件的目的。好了,废话不多说,先看下今天我做的这个小Demo的效果吧~~
- <span style="font-size:14px;">public class Taiji extends View {
- private Paint whitePaint;
- private Paint blackPaint;
-
- public Taiji(Context context) {
- this(context, null);
- }
-
- public Taiji(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public Taiji(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- initPaints();
- }
-
- private void initPaints() {
- whitePaint = new Paint();
- whitePaint.setAntiAlias(true);
- whitePaint.setColor(Color.WHITE);
-
- blackPaint = new Paint(whitePaint);
- blackPaint.setColor(Color.BLACK);
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- int width = canvas.getWidth();
- int height = canvas.getHeight();
-
- canvas.translate(width/2, height/2);
-
- canvas.drawColor(Color.RED);
- canvas.rotate(degrees);
-
- int radius = Math.min(width, height) / 2 - 100;
- RectF rect = new RectF(-radius, -radius, radius, radius);
- canvas.drawArc(rect, 90, 180, true, blackPaint);
- canvas.drawArc(rect, -90, 180, true, whitePaint);
-
- int smallRadius = radius / 2;
- canvas.drawCircle(0, -smallRadius, smallRadius, blackPaint);
- canvas.drawCircle(0, smallRadius, smallRadius, whitePaint);
-
-
- canvas.drawCircle(0, -smallRadius, smallRadius / 4, whitePaint);
- canvas.drawCircle(0, smallRadius, smallRadius / 4, blackPaint);
- }
-
- private float degrees = 0;
-
- public void setRotate(float degrees) {
- this.degrees = degrees;
- invalidate();
- }
- }</span>
手绘控件重难点就是对坐标要做到精确,逻辑清楚,要知道控件上所有的点都是通过onDraw()方法画出来的
2,在布局文件中引用
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="com.cuihai.customviewtaiji.MainActivity">
-
- <com.cuihai.customviewtaiji.view.Taiji
- android:id="@+id/custom"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </RelativeLayout>
3,由于本次操作比较简单所以main函数里面基本无需改动,
这篇关于仿太极图自定义view的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!