android TV ImageView选中控件
在android TV开发的时候,经常会遇到图片选中的情况,产品定义的选中效果一般有以下三种效果:
1 圆角
2 选中发光
3 尺寸放大
有三种方案供选择:
方案一:
UI提供圆角不发光图片、圆角发光图片,通过设置background 为StateListDrawable来选择不同状态的图片。
优点:集成速度快,方式简单。
缺点:每一个imageView切换状态的时候都要加载新的图片到内存,占用内存空间以及包体积。ui给的发光图片在分辨率较大的电视上容易产生毛边。
方案二:
UI提供矩形圆角图片,程序员通过设置imageView的parent 的 backgroud来实现发光。代码如下:
1 设置imageView的parent 的padding 为 xx像素。
2 设置imageView的parent 的backgroud为StateListDrawable,StateListDrawable代码如下所示。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/camera_status_select_bg" android:state_focused="true" />
<item android:drawable="@drawable/camera_status_select_bg" android:state_hovered="true" />
<item android:drawable="@drawable/camera_status_select_bg" android:state_selected="true" />
<item android:drawable="@drawable/camera_status_noselect_bg"></item>
</selector>
camera_status_select_bg:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/px_positive_20"></corners>
<solid android:color="#373B52"></solid>
<stroke android:color="#FFFFFF" android:width="@dimen/px_positive_2"></stroke>
</shape>
camera_status_noselect_bg:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/px_positive_20"></corners>
<solid android:color="#373B52"></solid>
</shape>
缺点:imageView父布局的padding不好控制描边的粗细,会有细微的差别。
方案三
自定义Imagview,通过paint.setXfermode来实现圆角和发光。代码如下。
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable == null || !(drawable instanceof BitmapDrawable)){
return;
}
int count = canvas.saveLayer(0,0,mWidth,mHeight,mPaint,Canvas.ALL_SAVE_FLAG);
mPaint.reset();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.BLUE);
roundRectf.set(0,0,mWidth,mHeight);
canvas.drawRoundRect(roundRectf,roundRadis,roundRadis,mPaint);
((BitmapDrawable)drawable).getPaint().setXfermode(xfermode);
super.onDraw(canvas);
if(focused){
mPaint.setXfermode(null);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokWidth);
mPaint.setColor(strokeColor);
canvas.drawRoundRect(roundRectf,roundRadis,roundRadis,mPaint);
}
canvas.restoreToCount(count);
if(ifScale){
if(focused){
scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1.0f, scaleRatio);
scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1.0f,scaleRatio );
}else {
scaleX = ObjectAnimator.ofFloat(this, "scaleX",scaleRatio , 1.0f);
scaleY = ObjectAnimator.ofFloat(this, "scaleY", scaleRatio, 1.0f);
}
animatorSet.setDuration(300);
animatorSet.setInterpolator(new DecelerateInterpolator());
animatorSet.play(scaleX).with(scaleY);//两个动画同时开始
animatorSet.start();
}
}
效果图:
优点:使用简单,可以实现上述三个功能。
该控件的详细demo请查看
https://download.csdn.net/download/chao18867105705/12692275