Android学习小demo(1)自定义View

本文介绍如何在Android开发中自定义View,通过继承View并重写OnMeasure和OnDraw方法来实现特定效果。文章以创建一组可自定义颜色、图片和旋转角度的正方形View为例,详细讲解了自定义属性、构造函数、测量和绘制过程。通过设置背景颜色、矩阵旋转和偏移,最终在布局文件中使用自定义View。
摘要由CSDN通过智能技术生成

在Android的开发中,很多时候系统提供的View已经不能够满足我们的要求,自定义View的需求自然而然就出来了。

实现自定义的View,需要去继承View类,并重写其OnMeasure和OnDraw方法,从而实现我们自己想要的效果。

其本质上就是封装了一些自己想要的效果,并使之能够被Framework识别,跟普通的系统的控件一样,可以重复利用。

下面就拿一个例子开始吧,先上一张效果图:



在这里,有六个正方形的View,每一个View的背景颜色都不一样,图片也不一样,旋转的角度也不一样,其实这三个都是自定义的属性来的。

1. 自定义属性。

在 res/values/文件夹中创建一个 attrs.xml 文件,定义我们的属性。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomRotateView">
        <attr name="drawable" format="reference"/>
        <attr name="degree" format="float" />
        <attr name="bgcolor" format="color" />
    </declare-styleable>    
</resources>

如上 name 是属性的名字, format 是属性对应值的类型, 其中reference 表明这个值是参考其他的资源文件,在xml 中使用这个属性的形式就是:"@drawable/photo1"

2. 定义好自定义属性之后,开始创建自定义的View。

很显然,一切得从继承View开始,代码如下:

package com.example.apidemostudy;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class CustomRotateView extends View {

	private final static String tag = "com.example.apidemostudy.CustomRotateView";

	private Bitmap mBitmap; // The bitmap to be drawn

	private int bgColor; // the BackgroundColor

	private float degree; // the angels to rotate

	private Matrix matrix; // the matrix to transform

	private int mWidth = 240, mHeight
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值