安卓自定义View实现文字环绕图片


这是我的第一篇博客,我也是安卓开发之路上的一个小菜鸟,写博客主要是为了记录自己曾经遇到的一些问题,回头看的时候能够找到,不至于每次开发每次现找现想现做,当然了我的记录能够帮助大家那更好了。第一篇博客,有不足之处,敬请谅解。

       最近项目需求,修改公共号纯文本推送样式,把文字前方加上一个公共号图标,搞了一天半,终于搞定了。虽然最后领导说不用这个样式了!!!我还是想把过程中遇到的坑记录下来,希望能帮到大家!

废话不多说先看我实现的效果:

       

        本来没觉得很困难,开始了我的百度之旅,皇天不负有心人,我找到了一篇关于鸿洋大神的一个自定义控件MixtureTextView,https://github.com/hongyangAndroid/MixtureTextView    自己写了一个Demo跑起来没问题,以为OK了,哪知道放到项目上的时候,因为采用的是ListView复用控件的时候出现了布局高度错乱问题,然后自己捣鼓半天也没捣鼓出来。然后我放弃了,继续找我的度哥,然后找到了http://blog.csdn.net/the01hierarch/article/details/7711658 这篇文章,我用了里面的view,放到listView中没有问题,但是这个控件字体大小,图片大小,字体颜色,都是固定的,然后我就修改了一下。下面是我修改的代码希望能帮到大家:

public class FloatImageText extends View {
    private Bitmap mBitmap;
    private final Rect bitmapFrame = new Rect();
    private final Rect tmp = new Rect();
    private int mTargetDentity = DisplayMetrics.DENSITY_DEFAULT;

    private Paint mPaint ;
    private String mText;
    private ArrayList<TextLine> mTextLines;
    private final int[] textSizes = new int[2];
    private int textColor=Color.BLACK;
    private int textSize=sp2px(14);


    public FloatImageText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();

    }

    public FloatImageText(Context context, AttributeSet attrs) {
        this(context, attrs,0);

    }


    public FloatImageText(Context context) {
        this(context,null);

    }

    private void init() {
        mTargetDentity = getResources().getDisplayMetrics().densityDpi;
        mTextLines = new ArrayList<TextLine>();
        mPaint=new Paint();
        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        mPaint.setAntiAlias(true);
    }

    public int sp2px(int spVal)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }
    public int dp2px(int dpVal)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());

    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int w = 0, h = 0;
        //图片大小
        w += bitmapFrame.width();
        h += bitmapFrame.height();

        //文本宽度
        if(null != mText && mText.length() > 0) {
            mTextLines.clear();
            int size = resolveSize(Integer.MAX_VALUE, widthMeasureSpec);
            measureAndSplitText(mPaint, mText, size);
            final int textWidth = textSizes[0], textHeight = textSizes[1];
            w += textWidth; //内容宽度
            if(h < textHeight) { //内容高度
                h = (int) textHeight;
            }
        }

        w = Math.max(w, getSuggestedMinimumWidth());
        h = Math.max(h, getSuggestedMinimumHeight());

        setMeasuredDimension(
                resolveSize(w, widthMeasureSpec),
                resolveSize(h+10, heightMeasureSpec));
    }

    @Override
    protected void onDraw(Canvas canvas) {

        //绘制图片
        if(null != mBitmap) {
            canvas.drawBitmap(mBitmap, null, bitmapFrame, null);
        }
        //绘制文本
        TextLine line;
        final int size = mTextLines.size();
        for(int i = 0; i < size; i++) {
            line = mTextLines.get(i);
            canvas.drawText(line.text, line.x, line.y, mPaint);
        }
        System.out.println(mTextLines);
    }


    public void setImageBitmap(Bitmap bm) {
        setImageBitmap(bm, null);
    }

    public void setImageBitmap(Bitmap bm, int left, int top) {
        setImageBitmap(bm, new Rect(left, top, 0, 0));
    }
    public void setImageBitmapWithSize(Bitmap bm, int left, int top,int imageWidth,int imageHeight) {
        setImageBitmap(bm, new Rect(left, top, 0, 0),imageWidth,imageHeight);
    }

    public void setImageBitmap(Bitmap bm, Rect bitmapFrame) {
        mBitmap = bm;
        computeBitmapSize(bitmapFrame);
        requestLayout();
        invalidate();
    }
    public void setImageBitmap(Bitmap bm, Rect bitmapFrame,int imageWidth,int imageHeight) {
        mBitmap = bm;
        computeBitmapSize(bitmapFrame,imageWidth,imageHeight);
        requestLayout();
        invalidate();
    }

    public void setText(String text) {
        mText = text;
        requestLayout();
        invalidate();
    }
    public void setTextColor(int color) {
        textColor = color;
        mPaint.setColor(color);
        requestLayout();
        invalidate();
    }
    public void setTextSize(int pxSize)
    {
        setTextSize(TypedValue.COMPLEX_UNIT_DIP, pxSize);
    }
    public void setTextSize(int unit, int size)
    {
        switch (unit)
        {
            case TypedValue.COMPLEX_UNIT_PX:
                textSize = size;
                break;
            case TypedValue.COMPLEX_UNIT_DIP:
                textSize = dp2px(size);
                break;
            case TypedValue.COMPLEX_UNIT_SP:
                textSize = sp2px(size);
                break;
        }
        mPaint.setTextSize(textSize);
        requestLayout();
        invalidate();
    }
    private void computeBitmapSize(Rect rect,int imageWidth,int imageHeight) {
        if(null != rect) {
            bitmapFrame.set(rect);
        }
        if(null != mBitmap) {
            if(rect.right == 0 && rect.bottom == 0) {
                final Rect r = bitmapFrame;
                r.set(r.left, r.top,
                        r.left + imageWidth,
                        r.top + imageHeight);

            }
        } else {
            bitmapFrame.setEmpty();
        }
    }
    private void computeBitmapSize(Rect rect) {
        if(null != rect) {
            bitmapFrame.set(rect);
        }
        if(null != mBitmap) {
            if(rect.right == 0 && rect.bottom == 0) {
                final Rect r = bitmapFrame;
                r.set(r.left, r.top,
                        r.left + 87,
                        r.top + 87);
            }
        } else {
            bitmapFrame.setEmpty();
        }
    }

    private void measureAndSplitText(Paint p, String content, int maxWidth) {
        Paint.FontMetrics fm = mPaint.getFontMetrics();
        final int lineHeight = (int) (fm.bottom - fm.top);

        final Rect r = new Rect(bitmapFrame);
        final int length = content.length();
        int start = 0, end = 0, offsetX = 0, offsetY = 0;
        int availWidth = maxWidth;
        TextLine line;
        boolean onFirst = true;
        boolean newLine = true;
        while(start < length) {
            end++;
            if(end == length) { //剩余的不足一行的文本
                if(start <= length - 1) {
                    if(newLine) offsetY += lineHeight;
                    line = new TextLine();
                    line.text = content.substring(start, end - 1);
                    line.x = offsetX;
                    line.y = offsetY;
                    mTextLines.add(line);
                }
                break;
            }
            Log.d("gc", "offsetY--------- = " + r.bottom);
            p.getTextBounds(content, start, end, tmp);
            if(onFirst) { //确定每个字符串的坐标
                onFirst = false;
                final int height = lineHeight + offsetY;
                if(r.top >= height) { //顶部可以放下一行文字
                    offsetX = 0;
                    availWidth = maxWidth;
                    newLine = true;
                } else if(newLine && (r.bottom >= height && r.left >= tmp.width())) { //中部左边可以放文字
                    offsetX = 0;
                    availWidth = r.left;
                    newLine = false;
                } else if(r.bottom >= height && maxWidth - r.right >= tmp.width()) { //中部右边
                    offsetX = r.right;
                    availWidth = maxWidth - r.right;
                    newLine = true;
                }else if(r.bottom >= height && maxWidth - r.right < tmp.width()) { //右边写不下
                    offsetX = 0;
                    availWidth = r.left;
                    offsetY += lineHeight;
                    newLine = true;
                }else { //底部
                    offsetX = 0;
                    availWidth = maxWidth;
                    if(offsetY < r.bottom) offsetY = r.bottom;
                    newLine = true;
                }
            }
            Log.d("gc", "offsetY1 = " + offsetY);
            if(tmp.width() > availWidth) { //保存一行能放置的最大字符串
                onFirst = true;
                line = new TextLine();
                line.text = content.substring(start, end - 1);
                line.x = offsetX;
                mTextLines.add(line);
                if(newLine) {
                    offsetY += lineHeight;
                    line.y = offsetY;
                    Log.d("gc", "offsetY1 = " + offsetY + " ^^^^^^^^^^^^^lineHeight = " + lineHeight);
                } else {
                    line.y = offsetY + lineHeight;
                    Log.d("gc", "offsetY2 = " + offsetY + " ^^^^^^^^^^^^^lineHeight = " + lineHeight);
                }
                start = end - 1;
            }
        }
        textSizes[1] = offsetY;
    }

    class TextLine {
        String text;
        int x;
        int y;

        @Override
        public String toString() {
            return "TextLine [text=" + text + ", x=" + x + ", y=" + y + "]";
        }
    }
}
建议:如果你的布局不需要复用,建议你还是使用鸿样大神的 https://github.com/hongyangAndroid/MixtureTextView 这个配置起来比较灵活。

如果你要复用的话这篇文章可以参考一下,希望对你有帮助!

不足:这个控件在放在ListView中复用,会出现稍微卡顿现象,这个希望各位大神能够修改完善。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值