自定义view基础练习

本文介绍了一种自定义Android视图组件的方法,通过重写`onDraw`方法实现绘图功能,包括画圆、矩形及显示位图。同时介绍了如何通过构造函数初始化画笔和位图资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

age cgg.com.simplecustomview.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import cgg.com.simplecustomview.R;

/**
 * author: Wanderer
 * date:   2018/1/7 20:43
 * email:  none
 * <p>
 * 一般情况下写三个构造方法 让其最终调用有三个参数的构造
 * 自定义控件重写的方法:
 * 1,
 */

public class MyCustomView extends View {

    private Paint paint;
    private Bitmap bitmap;

    // 供代码创建实例
    public MyCustomView(Context context) {
        this(context, null);
    }

    // 供XML布局文件是创建view 有属性参数
    public MyCustomView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    // 加了个样式
    public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 实例化画笔
        paint = new Paint();
        // 设置画笔样式
        paint.setStyle(Paint.Style.STROKE);
        // 设置画笔的颜色
        paint.setColor(Color.RED);

        // 解码图片
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cosplay02);
        // 修改图pain大小
        /**createScaledBitmap:
         * src 图片
         * dstWidth 宽
         * dstHeight 高
         * filte 是否过滤
         */
        bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
    }

    /**
     * canvas:画布
     * drawCircle:参数注释
     * float cx,   -->圆心的左边距
     * float cy,   -->圆心的上边距
     * float radius, ---> 圈圈的半径
     * Paint paint    ---> 画笔对象
     * <p>
     * drawRect:绘制矩形
     * left和right:矩形左边和右边距离父控件的左边边距
     * top和bottom:矩形上边和下边距离父控件的上边边距
     * Paint paint
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画个圈圈
        canvas.drawCircle(60, 50, 50, paint);

        // 画个矩形
        canvas.drawRect(10, 110, 100, 160, paint);

        // 画个图像
        canvas.drawBitmap(bitmap,10,180,null);
    }
}
效果图
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值