在图片或者其他View上添加文字、图标等标签,利用ViewBadger 可以轻松实现。关于ViewBadger 的使用,可以去下载官方实例。
效果图:
我现在要实现的功能是在一张图片上添加文字(文字前面有一个小图标动画),添加的文字在图片上可以任意拖动,所以对BadgeView.java文件进行适当修改。代码如下,可与源文件对比查看。
package com.example.imageaddtext;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabWidget;
import android.widget.TextView;
/**
* A simple text label view that can be applied as a "badge" to any given {@link android.view.View}.
* This class is intended to be instantiated at runtime rather than included in XML layouts.
*
* @author Jeff Gilfelt
*/
public class BadgeView extends TextView {
public static final int POSITION_TOP_LEFT = 1;
public static final int POSITION_TOP_RIGHT = 2;
public static final int POSITION_BOTTOM_LEFT = 3;
public static final int POSITION_BOTTOM_RIGHT = 4;
public static final int POSITION_CENTER = 5;
private static final int DEFAULT_MARGIN_DIP = 5;
private static final int DEFAULT_LR_PADDING_DIP = 5;
private static final int DEFAULT_CORNER_RADIUS_DIP = 8;
private static final int DEFAULT_POSITION = POSITION_TOP_LEFT;
private static final int DEFAULT_BADGE_COLOR = Color.parseColor("#CCFF0000"); //Color.RED;
private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
private static Animation fadeIn;
private static Animation fadeOut;
private Context context;
private View target;
private int badgePosition;
private int badgeMarginH;
private int badgeMarginV;
private int badgeColor;
private boolean isShown;
private ShapeDrawable badgeBg;
private int targetTabIndex;
//shark_5
private FrameLayout container;
private LinearLayout txtContainer;
private int lastX;
private int lastY;
private int mWidth;
private int mHeight;
private int contentTop = 0;
private int JLeft = 0;
private int JTop = 0;
public BadgeView(Context context) {
this(context, (AttributeSet) null, android.R.attr.textViewStyle);
}
public BadgeView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
/**
* Constructor -
*
* create a new BadgeView instance attached to a target {@link android.view.View}.
*
* @param context context for this view.
* @param target the View to attach the badge to.
*/
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target, 0);
}
/**
* Constructor -
*
* create a new BadgeView instance attached to a target {@link android.widget.TabWidget}
* tab at a given index.
*
* @param context context for this view.
* @param target the TabWidget to attach the badge to.
* @param index the position of the tab within the target.
*/
public BadgeView(Context context, TabWidget target, int index) {
this(context, null, android.R.attr.textViewStyle, target, index);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs, defStyle, null, 0);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target, int tabIndex) {
super(context, attrs, defStyle);
init(context, target, tabIndex);
}
private void init(Context context, View target, int tabIndex) {
Log.d("BadgeView","init");
container = new FrameLayout(context);
//添加LinearLayout,在其中放image和textview,我是想在text前面加一个image动画
txtContainer = new LinearLayout(context);
txtContainer.setGravity(Gravity.CENTER_VERTICAL);
this.context = context;
this.target = target;
this.targetTabIndex = tabIndex;
// apply defaults
badgePosition = DEFAULT_POSITION;
badgeMarginH = dipToPixels(DEFAULT_MARGIN_DIP);
badgeMarginV = badgeMarginH;
badgeColor = DEFAULT_BADGE_COLOR;
setTypeface(Typeface.DEFAULT_BOLD);
int paddingPixels = dipToPixels(DEFAULT_LR_PADDING_DIP);
setPadding(paddingPixels, 0, paddingPixels, 0);
setTextColor(DEFAULT_TEXT_COLOR);
fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(200);
fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(200);
isShown = false;
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
}
private void applyTo(View target) {
Log.d("BadgeView","applyTo(View target)");
LayoutParams lp = target.getLayoutParams();
ViewParent parent = target.getParent();
// FrameLayout container = new FrameLayout(context);
if (target instanceof TabWidget) {
Log.d("BadgeView","applyTo(View target) if");
// set target to the relevant tab child container
target = ((TabWidget) target).getChildTabViewAt(targetTabIndex);
this.target = target;
((ViewGroup) target).addView(container,
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
this.setVisibility(View.GONE);
container.addView(this);
} else {
Log.d("BadgeView","applyTo(View target) else");
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) parent;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index, lp);
container.addView(target);
txtContainer.setVisibility(View.GONE);
//在text前面加一个image图片的动画
ImageView imageView = new ImageView(context);
imageView.setImageResource(R.drawable.icon_them7);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);
imageView.setLayoutParams(layoutParams);
final Animation scaleAnimation= new
ScaleAnimation(0f,1f,0f,1f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
scaleAnimation.setDuration(1500); //动画持续时间
scaleAnimation.setRepeatMode(Animation.RESTART);
scaleAnimation.setRepeatCount(-1);
imageView.setAnimation(scaleAnimation); //设置动画
txtContainer.addView(imageView);
txtContainer.addView(this);
container.addView(txtContainer);
// container.addView(this);
group.invalidate();
}
}
//shark_5 获取Layout的截图
public Bitmap getLayoutBitmap(){
container.invalidate();
//shark_5
container.setDrawingCacheEnabled(true);
container.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
container.layout(0, 0, container.getMeasuredWidth(),
container.getMeasuredHeight());
container.buildDrawingCache();
Bitmap bitmap= container.getDrawingCache();
return bitmap;
}
/**
* Make the badge visible in the UI.
*
*/
public void show() {
show(false, null);
}
/**
* Make the badge visible in the UI.
*
* @param animate flag to apply the default fade-in animation.
*/
public void show(boolean animate) {
show(animate, fadeIn);
}
/**
* Make the badge visible in the UI.
*
* @param anim Animation to apply to the view when made visible.
*/
public void show(Animation anim) {
show(true, anim);
}
/**
* Make the badge non-visible in the UI.
*
*/
public void hide() {
hide(false, null);
}
/**
* Make the badge non-visible in the UI.
*
* @param animate flag to apply the default fade-out animation.
*/
public void hide(boolean animate) {
hide(animate, fadeOut);
}
/**
* Make the badge non-visible in the UI.
*
* @param anim Animation to apply to the view when made non-visible.
*/
public void hide(Animation anim) {
hide(true, anim);
}
/**
* Toggle the badge visibility in the UI.
*
*/
public void toggle() {
toggle(false, null, null);
}
/**
* Toggle the badge visibility in the UI.
*
* @param animate flag to apply the default fade-in/out animation.
*/
public void toggle(boolean animate) {
toggle(animate, fadeIn, fadeOut);
}
/**
* Toggle the badge visibility in the UI.
*
* @param animIn Animation to apply to the view when made visible.
* @param animOut Animation to apply to the view when made non-visible.
*/
public void toggle(Animation animIn, Animation animOut) {
toggle(true, animIn, animOut);
}
private void show(boolean animate, Animation anim) {
Log.d("BadgeView","show(boolean animate, Animation anim)");
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
if (animate) {
this.startAnimation(anim);
}
//shark_5
// this.setVisibility(View.VISIBLE);
txtContainer.setVisibility(View.VISIBLE);
isShown = true;
txtContainer.setClickable(true);
txtContainer.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
Log.d("onTouch", "----- onTouch action:" + action);
//相对于屏幕的位置
Log.d("", "----- onTouch XX:" + (int)event.getRawX());
Log.d("", "----- onTouch YY:" + (int)event.getRawY());
//相对于当前View的位置
Log.d("", "----- onTouch XX--:" + (int)event.getX());
Log.d("", "----- onTouch YY--:" + (int)event.getY());
switch (action) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
//记录在View中的位置
JLeft = (int)event.getX();
JTop = (int)event.getY();
break;
case MotionEvent.ACTION_MOVE:
int dx = 0;
int dy = 0;
/* touch位置超出target view范围不计算移动
* mWidth mHeight是target view 的宽高
* contentTop是target view距离屏幕顶部的距离
* JLeft JTop是在view(txtContainer)中的点击位置
*/
if((int)event.getRawX() < (mWidth - v.getWidth() + JLeft) && (int)event.getRawX() > JLeft){
dx =(int)event.getRawX() - lastX;
lastX = (int) event.getRawX();
}
if((int)event.getRawY() < (mHeight + contentTop - v.getHeight() + JTop) && (int)event.getRawY() > (contentTop + JTop)){
dy = (int)event.getRawY() - lastY;
lastY = (int) event.getRawY();
}
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
//使view(txtContainer)不超出target view范围
if(left < 0){
left = 0;
right = left + v.getWidth();
}
if(right > mWidth){
right = mWidth;
left = right - v.getWidth();
}
if(top < 0){
top = 0;
bottom = top + v.getHeight();
}
if(bottom > mHeight){
bottom = mHeight;
top = bottom - v.getHeight();
}
Log.d("", "----- onTouch left:" + left);
Log.d("", "----- onTouch top:" + top);
//重新设置view的位置
setBadgeMargin(left, top);
show();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
private void hide(boolean animate, Animation anim) {
Log.d("BadgeView","hide");
//shark_5
// this.setVisibility(View.GONE);
txtContainer.setVisibility(View.GONE);
if (animate) {
this.startAnimation(anim);
}
isShown = false;
}
private void toggle(boolean animate, Animation animIn, Animation animOut) {
if (isShown) {
hide(animate && (animOut != null), animOut);
} else {
show(animate && (animIn != null), animIn);
}
}
/**
* Increment the numeric badge label. If the current badge label cannot be converted to
* an integer value, its label will be set to "0".
*
* @param offset the increment offset.
*/
public int increment(int offset) {
CharSequence txt = getText();
int i;
if (txt != null) {
try {
i = Integer.parseInt(txt.toString());
} catch (NumberFormatException e) {
i = 0;
}
} else {
i = 0;
}
i = i + offset;
setText(String.valueOf(i));
return i;
}
/**
* Decrement the numeric badge label. If the current badge label cannot be converted to
* an integer value, its label will be set to "0".
*
* @param offset the decrement offset.
*/
public int decrement(int offset) {
return increment(-offset);
}
private ShapeDrawable getDefaultBackground() {
Log.d("BadgeView","getDefaultBackground");
int r = dipToPixels(DEFAULT_CORNER_RADIUS_DIP);
float[] outerR = new float[] {r, r, r, r, r, r, r, r};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
ShapeDrawable drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(badgeColor);
return drawable;
}
private void applyLayoutParams() {
Log.d("BadgeView","applyLayoutParams");
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Log.d("applyLayoutParams", "badgePosition:" + badgePosition);
Log.d("applyLayoutParams", "badgeMarginH:" + badgeMarginH);
Log.d("applyLayoutParams", "badgeMarginV:" + badgeMarginV);
switch (badgePosition) {
case POSITION_TOP_LEFT:
lp.gravity = Gravity.LEFT | Gravity.TOP;
lp.setMargins(badgeMarginH, badgeMarginV, 0, 0);
break;
case POSITION_TOP_RIGHT:
lp.gravity = Gravity.RIGHT | Gravity.TOP;
lp.setMargins(0, badgeMarginV, badgeMarginH, 0);
break;
case POSITION_BOTTOM_LEFT:
lp.gravity = Gravity.LEFT | Gravity.BOTTOM;
lp.setMargins(badgeMarginH, 0, 0, badgeMarginV);
break;
case POSITION_BOTTOM_RIGHT:
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
lp.setMargins(0, 0, badgeMarginH, badgeMarginV);
break;
case POSITION_CENTER:
lp.gravity = Gravity.CENTER;
lp.setMargins(0, 0, 0, 0);
break;
default:
break;
}
//shark_5
// setLayoutParams(lp);
txtContainer.setLayoutParams(lp);
}
/**
* Returns the target View this badge has been attached to.
*
*/
public View getTxtContainer() {
return txtContainer;
}
public View getTarget() {
return target;
}
/**
* Is this badge currently visible in the UI?
*
*/
@Override
public boolean isShown() {
return isShown;
}
/**
* Returns the positioning of this badge.
*
* one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT, POSTION_CENTER.
*
*/
public int getBadgePosition() {
return badgePosition;
}
/**
* Set the positioning of this badge.
*
* @param layoutPosition one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT, POSTION_CENTER.
*
*/
public void setBadgePosition(int layoutPosition) {
this.badgePosition = layoutPosition;
}
/**
* Returns the horizontal margin from the target View that is applied to this badge.
*
*/
public int getHorizontalBadgeMargin() {
return badgeMarginH;
}
/**
* Returns the vertical margin from the target View that is applied to this badge.
*
*/
public int getVerticalBadgeMargin() {
return badgeMarginV;
}
/**
* Set the horizontal/vertical margin from the target View that is applied to this badge.
*
* @param badgeMargin the margin in pixels.
*/
public void setBadgeMargin(int badgeMargin) {
this.badgeMarginH = badgeMargin;
this.badgeMarginV = badgeMargin;
}
/**
* Set the horizontal/vertical margin from the target View that is applied to this badge.
*
* @param horizontal margin in pixels.
* @param vertical margin in pixels.
*/
public void setBadgeMargin(int horizontal, int vertical) {
this.badgeMarginH = horizontal;
this.badgeMarginV = vertical;
}
//shark_5
public void setImageRect(int width, int height, int contentTop) {
this.mWidth = width;
this.mHeight = height;
this.contentTop = contentTop;
}
/**
* Returns the color value of the badge background.
*
*/
public int getBadgeBackgroundColor() {
return badgeColor;
}
/**
* Set the color value of the badge background.
*
* @param badgeColor the badge background color.
*/
public void setBadgeBackgroundColor(int badgeColor) {
this.badgeColor = badgeColor;
badgeBg = getDefaultBackground();
}
private int dipToPixels(int dip) {
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
return (int) px;
}
}
调用如下:
@SuppressLint("NewApi") private void drawText() {
//获得statusBar 和 titleBar高度,在OnCreate里面调用无效果
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight;
contentTop2 = statusBarHeight + titleBarHeight;
Log.d(TAG, "statusBarHeight:" + statusBarHeight);
Log.d(TAG, "titleBarHeight:" + titleBarHeight);
Log.d(TAG, "contentTop2:" + contentTop2);
mTextStr = mEditText1.getText().toString().isEmpty() ? "hello" : mEditText1.getText().toString();
mTextSize = Integer.valueOf(mEditText2.getText().toString());
final BadgeView badge = new BadgeView(this, mImageView);
badge.setText(mTextStr);
badge.setTextSize(mTextSize);
badge.setTextColor(Color.WHITE);
badge.setBadgeBackgroundColor(Color.parseColor("#74edb3"));
// badge.setBadgeBackgroundColor(0x74edb3);
//改进后的函数,必须调用 contentTop2是mImageView距离顶部的高度,此处是statusBar 加上 titleBar的高度
badge.setImageRect(mImageView.getWidth(), mImageView.getHeight(), contentTop2);
badge.show();
}
添加文字以后,可以使图片区域生产新的Bitmap对象
public Bitmap getLayoutBitmap(){
container.invalidate(); //<span style="font-family: Arial, Helvetica, sans-serif;">container为view对象,相当于截图的区域</span>
//shark_5
container.setDrawingCacheEnabled(true);
container.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
container.layout(0, 0, container.getMeasuredWidth(),
container.getMeasuredHeight());
container.buildDrawingCache();
Bitmap bitmap= container.getDrawingCache();
return bitmap;
}
Demo下载