利用TextView中的DrawableTop实现图片在文字上方,点击TextView能实现图片旋转

终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~

在今日头条里面Home按钮点击时候,能出现旋转的动画。这里模仿今日头条的Home按钮效果,通过自定义View来实现该效果。

先给出工程代码的GitHub地址:TopTextView

其实主要是在onDraw里面先绘制图片,然后再绘制text。旋转的动画通过animation-rotate实现。具体代码如下:

    @Override
    protected void onDraw(Canvas canvas) {

        if (mDrawableTop == null) {
            super.onDraw(canvas);
            return;
        }
        int drawablePadding = getCompoundDrawablePadding();
        int drawableWidth = this.mDrawableTop.getIntrinsicWidth();
        int drawableHeight = this.mDrawableTop.getIntrinsicHeight();
//        startDrawableX = (getWidth() >> 1) - ((drawablePadding + textWidth + drawableWidth) >> 1);
//        startDrawableY = (getHeight() >> 1) - (drawableHeight >> 1);
        startDrawableX = (getWidth()>>1) - (drawableWidth>>1);
        startDrawableY = (getHeight()>>1) - ((drawableHeight+textHeight+drawablePadding)>>1);
        //画旋转图片
        canvas.save();
        canvas.translate(startDrawableX, startDrawableY);
        this.mDrawableTop.draw(canvas);
        canvas.restore();

        //画文字
//        int boxht = this.getMeasuredHeight() - this.getExtendedPaddingTop() - this.getExtendedPaddingBottom();
//        int textht = getLayout().getHeight();
//        int  voffsetText = boxht - textht >> 1;
//        int boxht = this
        canvas.save();
//        canvas.translate((float) (startDrawableX + drawableWidth + drawablePadding), (float) (getExtendedPaddingTop() + voffsetText));
        canvas.translate((float)(getExtendedPaddingBottom()),(float)(startDrawableY+drawableHeight+drawablePadding));
        getLayout().draw(canvas);
        canvas.restore();
    }

为了实现重复绘制,需要重写下面函数:

 @Override
    public void invalidateDrawable(Drawable drawable) {
//        super.invalidateDrawable(drawable);
        final Rect dirty = drawable.getBounds();
        int scrollX = 0;
        int scrollY = 0;
        if(drawable == this.mDrawableTop){
            scrollX = startDrawableX;
            scrollY = startDrawableY;
        }
        this.invalidate(dirty.left + scrollX-2, dirty.top + scrollY-2, dirty.right + scrollX+2, dirty.bottom + scrollY+2);
    }

具体代码可以参考工程里面代码。

上一篇:Windows 7 下IP和MAC地址的绑定


下一篇:使用git时提示Could not create directory '%USERPROFILE%/.ssh'.percent_expand:unkown key %U