zoukankan      html  css  js  c++  java
  • 自定义控件-平铺图片

    使图片平铺背景

    在这里使用自定义控件为了使图片能够铺平整个控件背景。

    首先在样式里定义控件和属性

    style:
    <declare-styleable name="RatioLayout">
    <attr name="ratio" format="float"/>
    </declare-styleable>
    xml:
    
    
    <com.example.photo.custom.RatioLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:ratio="1">

    <ImageView
    android:id="@+id/module_layout_welcome_iv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/activity_welcome_iv" />
    </com.example.photo.custom.RatioLayout>
    java:
    public class RatioLayout extends FrameLayout {

    private float ratio;

    public RatioLayout(@NonNull Context context) {
    super(context);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    /*获取自定义控件的属性集合*/
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
    /*根据id,获取属性值RatioLayout_ratio系统默认控件名_属性名*/
    ratio = typedArray.getFloat(R.styleable.RatioLayout_ratio, 0);
    /*回收*/
    typedArray.recycle();
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    /*获取模式*/
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    /*获取大小*/
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    /*MeasureSpec.AT_MOST 类似match_parent
    * MeasureSpec.EXACTLY 类似wrap_content
    * MeasureSpec.UNSPECIFIED 未定义*/

    if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && ratio > 0) {
    /*根据布局推算出图片宽度*/
    int imageWidth=widthSize-getPaddingEnd()-getPaddingStart();
    /*根据图片宽度,宽高比,推算出图片高度*/
    int imageHeight= (int) (imageWidth/ratio+0.5f);
    /*根据图片高度算出控件高度*/
    heightSize=imageHeight+getPaddingTop()+getPaddingBottom();
    /*重新定义*/
    heightMeasureSpec= MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    }
     
     
  • 相关阅读:
    JAVA的中文字符乱码问题
    JAVA SSH 框架介绍
    MySQL必备命令
    java文件操作
    注意事项
    再探java基础——throw与throws
    table与div互相嵌套注意
    数列F[19] + F[13]的值
    统计各类字符个数
    长理ACM 14-星期几(谌海军)
  • 原文地址:https://www.cnblogs.com/JiaoYF/p/13750693.html
Copyright © 2011-2022 走看看