首页 > 其他分享 >带标记的ImageView,图片可以设置成圆角

带标记的ImageView,图片可以设置成圆角

时间:2023-04-06 22:04:41浏览次数:42  
标签:圆角 return 标记 int private import ImageView android public


先看图



带标记的ImageView,图片可以设置成圆角_android



这个功能可以很方便的为一张图片设置一个标记,这在促销的时候很是有效

<com.mb.bgfitting.view.SimpleTagImageView        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/item_0"
        android:layout_width="80dp"
        android:layout_height="80dp" 
        android:contentDescription="@null"
        app:simple_tag_textSize="@dimen/font_middle"
        app:simple_corner_distance="20dp"
        app:simple_tag_text="50%off"
        app:simple_tag_background_color="#AA27CDC0"
        app:simple_tag_orientation="left_top"
        app:simple_tag_width="16dip"
        app:simple_tag_textColor="@android:color/white"
        app:simple_tag_enable="true"
        app:simple_tag_round_radius="8dp"
        />




源码:


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class SimpleTagImageView extends ImageView {

    public static final String TAG = "SimpleTagImageView";

    public  static final byte LEFT_TOP = 0x00;

    public  static final byte RIGHT_TOP = 0x01;

    public  static final byte LEFT_BOTTOM = 0x02;

    public  static final byte RIGHT_BOTTOM = 0x03;

    private static final float THE_SQUARE_ROOT_OF_2 = (float) Math.sqrt(2);

    private static final int DEFAULT_TAG_WIDTH = 20;

    private static final int DEFAULT_CORNER_DISTANCE = 20;

    private static final int DEFAULT_TAG_BACKGROUND_COLOR = 0x9F27CDC0;

    private static final int DEFAULT_TAG_TEXT_SIZE = 15;

    private static final int DEFAULT_TAG_TEXT_COLOR = 0xFFFFFFFF;

    private float mCornerDistance;

    private float mTagWidth;

    private int mTagBackgroundColor;

    private Path mPath;

    private Paint mPaint;

    private String mTagText;

    private int mTagTextSize;

    private Paint mTextPaint;

    private Rect mTagTextBound;

    private int mTagTextColor;

    private float mDensity;

    private int mTagOrientation;

    private MyPoint startPoint;

    private MyPoint endPoint;

    private Paint mBitmapPaint;

    private RectF mRoundRect;

    private boolean mTagEnable;

    private int mRoundRadius;

    public SimpleTagImageView(Context context) {
        this(context, null);
    }

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

    public SimpleTagImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mDensity = context.getResources().getDisplayMetrics().density;
        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.SimpleTagImageView,defStyleAttr,0);
        mTagOrientation = a.getInteger(R.styleable.SimpleTagImageView_simple_tag_orientation,0);
        mTagWidth = a.getDimensionPixelSize(R.styleable.SimpleTagImageView_simple_tag_width, dip2px(DEFAULT_TAG_WIDTH));
        mCornerDistance = a.getDimensionPixelSize(R.styleable.SimpleTagImageView_simple_corner_distance,dip2px(DEFAULT_CORNER_DISTANCE));
        mTagBackgroundColor = a.getColor(R.styleable.SimpleTagImageView_simple_tag_background_color,DEFAULT_TAG_BACKGROUND_COLOR);
        mTagText = a.getString(R.styleable.SimpleTagImageView_simple_tag_text);
        mTagTextSize = a.getDimensionPixelSize(R.styleable.SimpleTagImageView_simple_tag_textSize, dip2px(DEFAULT_TAG_TEXT_SIZE));
        mTagTextColor = a.getColor(R.styleable.SimpleTagImageView_simple_tag_textColor, DEFAULT_TAG_TEXT_COLOR);
        mTagEnable = a.getBoolean(R.styleable.SimpleTagImageView_simple_tag_enable,true);
        mRoundRadius = a.getDimensionPixelSize(R.styleable.SimpleTagImageView_simple_tag_round_radius,0);
        a.recycle();
        if(TextUtils.isEmpty(mTagText))mTagText = "";
        mPaint = new Paint();
        mPath = new Path();
        mTextPaint = new Paint();
        mTagTextBound = new Rect();
        startPoint = new MyPoint();
        endPoint = new MyPoint();
        mRoundRect = new RectF();
    }

    /**
     *
     * @param textSize unit:dip
     */
    public void setTagTextSize(int textSize) {
        this.mTagTextSize = dip2px(textSize);
        invalidate();
    }

    public int getTagTextSize(){
        return mTagTextSize;
    }

    /**
     *
     * @param cornerDistance unit:dip
     */
    public void setCornerDistance(int cornerDistance) {
        if(this.mCornerDistance == cornerDistance)return;
        this.mCornerDistance = dip2px(cornerDistance);
        invalidate();
    }

    /**
     *
     * @return unit:dip
     */
    public int getCornerDistance() {
        return px2dip(this.mCornerDistance);
    }

    public int getTagTextColor() {
        return this.mTagTextColor;
    }

    public void setTagTextColor(int tagTextColor) {
        if(this.mTagTextColor == tagTextColor)return;
        this.mTagTextColor = tagTextColor;
        invalidate();
    }

    public String getTagText() {
        return this.mTagText;
    }

    public void setTagText(String tagText){
        if(tagText.equals(this.mTagText))return;
        this.mTagText = tagText;
        invalidate();
    }

    public void setTagBackgroundColor(int tagBackgroundColor) {
        if(this.mTagBackgroundColor == tagBackgroundColor)return;
        this.mTagBackgroundColor = tagBackgroundColor;
        invalidate();
    }

    public int getTagBackgroundColor() {
        return this.mTagBackgroundColor;
    }

    /**
     * @return unit:dip
     */
    public int getTagWidth() {
        return px2dip(this.mTagWidth);
    }

    /**
     *
     * @param tagWidth unit:dip
     */
    public void setTagWidth(int tagWidth) {
        this.mTagWidth = dip2px(tagWidth);
        invalidate();
    }

    /**
     * @return  0 : left_top
     *          1 : right_top
     *          2 : left_bottom
     *          3 : right_bottom
     */
    public int getTagOrientation() {
        return mTagOrientation;
    }

    /**
     *
     * @param tagOrientation {@link #LEFT_TOP} or
     *                       {@link #LEFT_BOTTOM} or
     *                       {@link #RIGHT_TOP} or
     *                       {@link #RIGHT_BOTTOM}
     */
    public void setTagOrientation(int tagOrientation) {
        if(tagOrientation == this.mTagOrientation)return;
        this.mTagOrientation = tagOrientation;
        invalidate();
    }

    public void setTagEnable(boolean tagEnable) {
        if(this.mTagEnable == tagEnable) return ;
        this.mTagEnable = tagEnable;
        invalidate();
    }

    public boolean getTagEnable() {
        return this.mTagEnable;
    }

    public  int getTagRoundRadius() {
        return this.mRoundRadius;
    }

    public void setTagRoundRadius(int roundRadius) {
        if(this.mRoundRadius == roundRadius) return;
        this.mRoundRadius = roundRadius;
        invalidate();
    }

    @Override
    protected void onDraw(@SuppressWarnings("NullableProblems") Canvas mCanvas) {
        if(mRoundRadius == 0) {
            super.onDraw(mCanvas);
        }else {
            Drawable d = getDrawable();
            if(d == null) return;
            if(d.getIntrinsicWidth() == 0 || d.getIntrinsicHeight() == 0) return;
            setupBitmapPaint();
            mRoundRect.set(getPaddingLeft(),getPaddingTop(),getMeasuredWidth() - getPaddingRight(),getMeasuredHeight() - getPaddingBottom());
            mCanvas.drawRoundRect(mRoundRect, mRoundRadius, mRoundRadius, mBitmapPaint);
        }

        if(mTagWidth > 0 && mTagEnable) {
            float rDistance = mCornerDistance + mTagWidth/2;
            chooseTagOrientation(rDistance);
            mTextPaint.setTextSize(mTagTextSize);
            mTextPaint.getTextBounds(mTagText,0,mTagText.length(),mTagTextBound);
            mPaint.setDither(true);
            mPaint.setAntiAlias(true);
            mPaint.setColor(mTagBackgroundColor);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeJoin(Paint.Join.ROUND);
            mPaint.setStrokeCap(Paint.Cap.SQUARE);
            mPaint.setStrokeWidth(mTagWidth);
            mPath.reset();
            mPath.moveTo(startPoint.x, startPoint.y);
            mPath.lineTo(endPoint.x, endPoint.y);
            mCanvas.drawPath(mPath, mPaint);
            mTextPaint.setColor(mTagTextColor);
            mTextPaint.setTextSize(mTagTextSize);
            mTextPaint.setAntiAlias(true);
//          斜边长度
            float hypotenuse = THE_SQUARE_ROOT_OF_2 * rDistance;
            mCanvas.drawTextOnPath(mTagText, mPath, hypotenuse / 2 - mTagTextBound.width() / 2,
                    mTagTextBound.height() / 2, mTextPaint);
        }
    }

    private void chooseTagOrientation(float rDistance) {
        int mWidth = getMeasuredWidth();
        int mHeight = getMeasuredHeight();
        switch (mTagOrientation) {
            case 0:
                startPoint.x = 0;
                startPoint.y = rDistance;
                endPoint.x = rDistance;
                endPoint.y = 0;
                break;
            case 1:
                startPoint.x = mWidth - rDistance;
                startPoint.y = 0;
                endPoint.x = mWidth;
                endPoint.y = rDistance;
                break;
            case 2:
                startPoint.x = 0;
                startPoint.y = mHeight - rDistance;
                endPoint.x = rDistance;
                endPoint.y = mHeight;
                break;
            case 3:
                startPoint.x = mWidth - rDistance;
                startPoint.y = mHeight;
                endPoint.x = mWidth;
                endPoint.y = mHeight - rDistance;
                break;
        }
    }

    private void setupBitmapPaint() {
        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }
        Bitmap mBitmap = drawableToBitmap(drawable);
        BitmapShader mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        if(getScaleType() != ScaleType.FIT_XY){
            Log.w(TAG,String.format("Now scale type just support fitXY,other type invalid"));
        }
        //now scale type just support fitXY
        //todo support all scale type
        Matrix mMatrix = new Matrix();
        mMatrix.setScale(getWidth() * 1.0f / mBitmap.getWidth(), getHeight() * 1.0f / mBitmap.getHeight());
        mBitmapShader.setLocalMatrix(mMatrix);
        if(mBitmapPaint == null) {
            mBitmapPaint = new Paint();
            mBitmapPaint.setDither(false);
            mBitmapPaint.setAntiAlias(true);
            mBitmapPaint.setShader(mBitmapShader);
        }
    }

    private int dip2px(int dip) {
        return (int)(mDensity * dip + 0.5f);
    }

    private int px2dip(float px) {
        return (int)(px/mDensity + 0.5f);
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            return bitmapDrawable.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    static class MyPoint {
        float x;
        float y;
    }
}




属性:


<?xml version="1.0" encoding="utf-8"?><resources>
    <declare-styleable name="SimpleTagImageView">
        <attr name="simple_corner_distance" format="dimension" />
        <attr name="simple_tag_width" format="dimension"/>
        <attr name="simple_tag_background_color" format="color"/>
        <attr name="simple_tag_text" format="string"/>
        <attr name="simple_tag_textSize" format="dimension" />
        <attr name="simple_tag_textColor" format="color"/>
        <attr name="simple_tag_orientation" format="enum">
            <enum name="left_top" value="0"/>
            <enum name="right_top" value="1"/>
            <enum name="left_bottom" value="2"/>
            <enum name="right_bottom" value="3"/>
        </attr>
        <attr name="simple_tag_enable" format="boolean"/>
        <attr name="simple_tag_round_radius" format="dimension"/>
    </declare-styleable>
</resources>






一个为ImageView添加徽章,标记(badge)的库


http://www.jcodecraeer.com/a/opensource/2015/1125/3720.html


Android标签控件


https://github.com/H07000223/FlycoLabelView



使用 supportV4 的 RoundedBitmapDrawable 实现圆角




可配置的迷你版轻量级 Label 辅助类


https://github.com/yanbober/AvatarLabelView


  • 带标记的ImageView,图片可以设置成圆角_2d_02

  • 大小: 24.6 KB
  • 查看图片附件

标签:圆角,return,标记,int,private,import,ImageView,android,public
From: https://blog.51cto.com/u_5454003/6174219

相关文章

  • ImageView翻转效果
    点击图中的星星开始翻转源码:importandroid.content.Context;importandroid.content.res.TypedArray;importandroid.graphics.Bitmap;importandroid.graphics.Camera;importandroid.graphics.Matrix;importandroid.graphics.drawable.BitmapDrawab......
  • Blender网格建模插件MESHmachine倒角和圆角:扁平 化
    推荐:将NSDT场景编辑器加入你的3D工具链编辑模式ye使用拼合工具,您可以拼合单个或多个多边形,并且可以在2种模式下展平:沿边或沿法线。选择展平可以采取2种选择。您可以选择 3个折点或多个多边形,其中一个处于活动状态。如果选择3个顶点,则连接多边形的所有顶点都将根据3个顶点......
  • 垃圾回收之三色标记法
    关于垃圾回收算法,基本就是那么几种:标记-清除、标记-复制、标记-整理。在此基础上可以增加分代(新生代/老年代),每代采取不同的回收算法,以提高整体的分配和回收效率。无论使用哪种算法,标记总是必要的一步。你不先找到垃圾,怎么进行回收?今天一起看下三色标记法。一、如何标记在GC领......
  • Android ImageView 详述
    结构继承关系publicclassView.OnClickListnerextendsView java.lang.Objectandroid.view.Viewandroid.widget.ImageView类概述显示任意图像,例如图标。ImageView类可以加载各种来源的图片(如资源或图片库),需要计算图像的尺寸,比便它可以在其他布局中使用,并提供例如缩放和着色(渲染)各......
  • css 设置 div等于屏幕的时候直角,小于屏幕圆角
    .card{border-radius:clamp(0px,((100vw-4px)-100%)*9999,8px);}clamp()clamp()函数的作用是把一个值限制在一个上限和下限之间,当这个值超过最小值和最大值的范围时,在最小值和最大值之间选择一个值使用。它接收三个参数:最小值、首选值、最大值。......
  • 【pytest】 pytest自定义标记 PytestUnknownMarkWarning处理方式
    未注册标记会出现warningssummary-- PytestUnknownMarkWarningPytestUnknownMarkWarning:Unknownpytest.mark.demo-isthisatypo?Youcanregistercustommarkstoavoidthiswarning-fordetails,seehttps://docs.pytest.org/en/stable/how-to/mark.html@......
  • 三色标记法
    在遍历对象图的过程中,把需要遍历的对象按照“是否访问过”分为以下三种颜色。白色:表示对象尚未被垃圾回收器访问过。显然,在可达性分析刚刚开始的阶段,所有的对象都是白色......
  • Android开发-Android常用组件-ImageView图像视图
    4.4 ImageView(图像视图)ImageView见名知意,就是用来显示图像的一个View或者说控件 需掌握的知识点:ImageView的src属性和blackground的区别;adjustViewBounds设置......
  • 点击图片标记红点
    /**获取图片的xy坐标【点击】*/getMouseXY(e){console.log('dadada')//offset是点击当前对象【这里点击img】的偏移量this.imgX=......
  • CSS 圆角输入框
    ff,chrome,safari下面可以用圆角边框来实现,IE下面还是用背景比较好 Java代码  input{height:18px;inline-height:18p......