最近研究自定义控件,看到一个很有意思的类LightingColorFilter(如果有这个需求:点击一个图片改变他的颜色,而不是替换成另一张点击效果的图片。那么这个类就有用了),打算用这个实现一个点击效果,下面附上代码:

package com.example.recyclerviewdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;


public class SelectorView extends View {
private Context mContext;// 上下文环境引用
private Paint mPaint;
private Bitmap bitmap;//位图
private boolean isClick;//标记是否被点击了

public SelectorView(Context context) {
super(context);
}

public SelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaint();
initRes(context);
//点击事件
setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
//判断是否点击
if (isClick) {
mPaint.setColorFilter(null);
isClick = false;
}else {
mPaint.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0X00FFFF00));//这个地方设置的是LightingColorFilter()
isClick = true;
}
invalidate();
}
});
}
private void initRes(Context context) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.b);//带点击改变的图片
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, 0, 0, mPaint);
}

private void initPaint(){
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
}
布局中添加:

<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.example.recyclerviewdemo.MainActivity" >

<com.example.recyclerviewdemo.SelectorView
android:id="@+id/cv_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>

代码中使用:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SelectorView) findViewById(R.id.cv_circle);
}




更多相关文章

  1. Android 实现从本地读取图片更改聊天背景
  2. Android从零开搞系列:自定义View(15)仿天天美剧拖动卡片的效果(下)
  3. android 打开系统相册得到路径 上传图片到php服务器
  4. Android中如何有效的加载图片
  5. php 图片验证码用javascript验证
  6. Java图片识别技术原理-只取图片像素。。。
  7. javascript实现拖动层效果代码(许愿墙)
  8. 「小程序JAVA实战」小程序头像图片上传(中)(44)
  9. java操作ftp实现文件的上传下载(适用于图片文档服务器)

随机推荐

  1. 深度好文 |Matplotlib 可视化最有价值的 5
  2. Oracle基本操作+Java连接Oracle
  3. Python英语 - Issue16
  4. 思科dhcp和链路捆绑
  5. 2019年1-5月文章汇总 | Python数据之道
  6. Android中的UI线程详解
  7. 可视化神器 Plotly Express 合并到 Plotl
  8. JVM的新生代跟老年代
  9. 用Python快速分析和预测股票价格
  10. 机器学习爱好者必读的入门指南