Java Code Examples for android.content.res.Resources#getDisplayMetrics()

The following examples show how to use android.content.res.Resources#getDisplayMetrics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReadStyleActivity.java    From a with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 自定义背景
 */
public void setCustomBg(Uri uri) {
    try {
        bgPath = FileUtils.getPath(this, uri);
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        Bitmap bitmap = BitmapUtil.getFitSampleBitmap(bgPath, width, height);
        bgCustom = 2;
        bgDrawable = new BitmapDrawable(getResources(), bitmap);
        upBg();
    } catch (Exception e) {
        e.printStackTrace();
        toast(e.getMessage(), ERROR);
    }
}
 
Example 2
Source File: TextView.java    From Genius-Android with Apache License 2.0 6 votes vote down vote up
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    if (attrs == null)
        return;

    final Context context = getContext();
    final Resources resources = getResources();
    final float density = resources.getDisplayMetrics().density;

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView, defStyleAttr, defStyleRes);
    int border = a.getInt(R.styleable.TextView_gBorder, 0);
    int borderSize = a.getDimensionPixelOffset(R.styleable.TextView_gBorderSize, (int) density);
    int borderColor = a.getColor(R.styleable.TextView_gBorderColor, UiCompat.getColor(resources, R.color.g_default_base_secondary));
    String fontFile = a.getString(R.styleable.TextView_gFont);
    a.recycle();

    setBorder(border, borderSize, borderColor);

    // Check for IDE preview render
    if (!this.isInEditMode() && fontFile != null && fontFile.length() > 0) {
        Typeface typeface = Ui.getFont(getContext(), fontFile);
        if (typeface != null) setTypeface(typeface);
    }
}
 
Example 3
Source File: AdvanceDrawer6Activity.java    From Drawer-Behavior with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void setLocale(Locale locale) {
    Resources resources = getResources();
    Configuration configuration = resources.getConfiguration();
    DisplayMetrics displayMetrics = resources.getDisplayMetrics();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        configuration.setLocale(locale);
    } else {
        configuration.locale = locale;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        getApplicationContext().createConfigurationContext(configuration);
    } else {
        resources.updateConfiguration(configuration, displayMetrics);
    }
}
 
Example 4
Source File: LeafUtil.java    From LeafChart with Apache License 2.0 5 votes vote down vote up
/**
 * 给定背景图,得到一个带有文字的Bitmap
 * @param gContext
 * @param gResId
 * @param gText
 * @return
 */
public static Bitmap getBitMapWithText(Context gContext, int gResId, String gText) {
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);

    Bitmap.Config bitmapConfig =
            bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(bitmap);
    // new antialised Paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.WHITE);
    // text size in pixels
    paint.setTextSize((int) (12 * scale));
    // text shadow
    // paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
    // draw text to the Canvas center
    Rect bounds = new Rect();
    paint.getTextBounds(gText, 0, gText.length(), bounds);
    int x = (bitmap.getWidth() - bounds.width()) / 2;
    int y = (bitmap.getHeight() + bounds.height()) / 2 - 5;
    canvas.drawText(gText, x, y, paint);
    return bitmap;
}
 
Example 5
Source File: MediaPlayer.java    From HeroVideo-master with Apache License 2.0 5 votes vote down vote up
public float pixel2dip(Context context, float n){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = n / (metrics.densityDpi / 160f);
    return dp;

}
 
Example 6
Source File: Utils.java    From MapViewPager with Apache License 2.0 5 votes vote down vote up
public static int getNavigationBarWidth(Context context) {
    if (!hasNavigationBar(context)) return 0;
    Resources r = context.getResources();
    DisplayMetrics dm = r.getDisplayMetrics();
    Configuration config = r.getConfiguration();
    boolean canMove = dm.widthPixels != dm.heightPixels && config.smallestScreenWidthDp < 600;
    if (canMove && config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        int id = r.getIdentifier("navigation_bar_width", "dimen", "android");
        if (id > 0) return r.getDimensionPixelSize(id);
    }
    return 0;
}
 
Example 7
Source File: SkinCompatManager.java    From Android-skin-support with MIT License 5 votes vote down vote up
/**
 * 获取皮肤包资源{@link Resources}.
 *
 * @param skinPkgPath sdcard中皮肤包路径.
 * @return
 */
@Nullable
public Resources getSkinResources(String skinPkgPath) {
    try {
        AssetManager assetManager = AssetManager.class.newInstance();
        Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, skinPkgPath);

        Resources superRes = mAppContext.getResources();
        return new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Source File: BitmapUtils.java    From react-native-sunmi-inner-printer with MIT License 5 votes vote down vote up
public static Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {  
    	  Log.i(TAG, "drawTextToBitmap = " + gText);
		  Resources resources = gContext.getResources();  
		  float scale = resources.getDisplayMetrics().density;  
		  Bitmap bitmap =   
		     BitmapFactory.decodeResource(resources, gResId);  
		   
		  Bitmap.Config bitmapConfig =
		      bitmap.getConfig();  
		  // set default bitmap config if none   
		 if(bitmapConfig == null) {  
		    bitmapConfig = Bitmap.Config.ARGB_8888;
		  }  
		  // resource bitmaps are imutable,    
		  // so we need to convert it to mutable one   
		  bitmap = bitmap.copy(bitmapConfig, true);  
		   
		  Canvas canvas = new Canvas(bitmap);  
		  // new antialised Paint   
		  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  
		  // text color - #3D3D3D   
		  paint.setColor(Color.WHITE);  
		  // text size in pixels   
		  paint.setTextSize((int) (12 * scale));  
		  // text shadow   
//		  paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);  
		   
		  // draw text to the Canvas center   
		  Rect bounds = new Rect();  
		  paint.getTextBounds(gText, 0, gText.length(), bounds);  
		  int x = (bitmap.getWidth() - bounds.width())/2;  
		  int y = (bitmap.getHeight())/2 + (int)scale*2;  
		   
		  canvas.drawText(gText,  x, y, paint);  
	      
		  canvas.save();
	      canvas.restore();
		   
		  return bitmap;  
	}
 
Example 9
Source File: LoadingActivity.java    From MegviiFacepp-Android-SDK with Apache License 2.0 5 votes vote down vote up
protected void showLanguage(String language) {
        //设置应用语言类
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);
        mSharedUtil.saveStringValue("language", language);
//        freshView();
    }
 
Example 10
Source File: IconUtilities.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public IconUtilities(Context context) {
    final Resources resources = context.getResources();
    DisplayMetrics metrics = mDisplayMetrics = resources.getDisplayMetrics();
    final float density = metrics.density;
    final float blurPx = 5 * density;

    mIconWidth = mIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);
    mIconTextureWidth = mIconTextureHeight = mIconWidth + (int)(blurPx*2);
    mCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
            Paint.FILTER_BITMAP_FLAG));
}
 
Example 11
Source File: VirtualCore.java    From container with GNU General Public License v3.0 5 votes vote down vote up
public Resources getResources(String pkg) {
    AppSetting appSetting = findApp(pkg);
    if (appSetting != null) {
        AssetManager assets = mirror.android.content.res.AssetManager.ctor.newInstance();
        mirror.android.content.res.AssetManager.addAssetPath.call(assets, appSetting.apkPath);
        Resources hostRes = context.getResources();
        return new Resources(assets, hostRes.getDisplayMetrics(), hostRes.getConfiguration());
    }
    return null;
}
 
Example 12
Source File: DpUtil.java    From RecordView with Apache License 2.0 4 votes vote down vote up
public static float toDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}
 
Example 13
Source File: DeviceScreen.java    From react-native-navigation with MIT License 4 votes vote down vote up
public static int width(Resources resources) {
    return resources.getDisplayMetrics().widthPixels;
}
 
Example 14
Source File: ViewUtil.java    From Phonograph with GNU General Public License v3.0 4 votes vote down vote up
public static float convertDpToPixel(float dp, Resources resources) {
    DisplayMetrics metrics = resources.getDisplayMetrics();
    return dp * metrics.density;
}
 
Example 15
Source File: Loading.java    From Genius-Android with Apache License 2.0 4 votes vote down vote up
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    final Context context = getContext();
    final Resources resource = getResources();

    if (attrs == null) {
        // default we init a circle style loading drawable
        setProgressStyle(STYLE_CIRCLE);
        return;
    }

    final float density = resource.getDisplayMetrics().density;
    // default size 2dp
    final int baseSize = (int) (density * 2);

    // Load attributes
    final TypedArray a = context.obtainStyledAttributes(
            attrs, R.styleable.Loading, defStyleAttr, defStyleRes);

    int bgLineSize = a.getDimensionPixelOffset(R.styleable.Loading_gBackgroundLineSize, baseSize);
    int fgLineSize = a.getDimensionPixelOffset(R.styleable.Loading_gForegroundLineSize, baseSize);

    int bgColor = 0;// transparent color
    ColorStateList colorStateList = a.getColorStateList(R.styleable.Loading_gBackgroundColor);
    if (colorStateList != null)
        bgColor = colorStateList.getDefaultColor();

    int fgColor = Color.BLACK;
    int[] fgColorArray = null;
    try {
        fgColor = a.getColor(R.styleable.Loading_gForegroundColor, 0);
    } catch (Exception ignored) {
        int fgColorId = a.getResourceId(R.styleable.Loading_gForegroundColor, R.array.g_default_loading_fg);
        // Check for IDE preview render
        if (!isInEditMode()) {
            TypedArray taColor = resource.obtainTypedArray(fgColorId);
            int length = taColor.length();
            if (length > 0) {
                fgColorArray = new int[length];
                for (int i = 0; i < length; i++) {
                    fgColorArray[i] = taColor.getColor(i, Color.BLACK);
                }
            } else {
                String type = resource.getResourceTypeName(fgColorId);
                try {
                    switch (type) {
                        case "color":
                            fgColor = resource.getColor(fgColorId);
                            break;
                        case "array":
                            fgColorArray = resource.getIntArray(fgColorId);
                            break;
                        default:
                            fgColorArray = resource.getIntArray(R.array.g_default_loading_fg);
                            break;
                    }
                } catch (Exception e) {
                    fgColorArray = resource.getIntArray(R.array.g_default_loading_fg);
                }
            }
            taColor.recycle();
        }
    }

    int style = a.getInt(R.styleable.Loading_gProgressStyle, 1);
    boolean autoRun = a.getBoolean(R.styleable.Loading_gAutoRun, true);

    float progress = a.getFloat(R.styleable.Loading_gProgressFloat, 0);

    a.recycle();

    setProgressStyle(style);
    setAutoRun(autoRun);
    setProgress(progress);

    setBackgroundLineSize(bgLineSize);
    setForegroundLineSize(fgLineSize);
    setBackgroundColor(bgColor);

    if (fgColorArray == null) {
        setForegroundColor(fgColor);
    } else {
        setForegroundColor(fgColorArray);
    }
}
 
Example 16
Source File: RectDrawable.java    From holoaccent with Apache License 2.0 4 votes vote down vote up
public RectDrawable(Resources res, int fillColor, float borderWidthDp, int borderColor) {
	DisplayMetrics metrics = res.getDisplayMetrics();
	mState = new RectConstantState(metrics, fillColor, borderWidthDp, borderColor);
	mBorderPaint = initBorderPaint(metrics, borderWidthDp, borderColor);
	mFillPaint = initFillPaint(fillColor);
}
 
Example 17
Source File: HistoryFragment.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
public HistoryAdapter(MainActivity activity) {
    super(activity, 0);
    Resources resources = activity.getResources();
    inflater = LayoutInflater.from(activity);
    drawablePadding = (int) (resources.getDisplayMetrics().density * 5 + 0.5f);
    
    long midnight = getMidnight();
    int current = 0;
    int previous = -1;
    if (lastClosed.size() > 0) {
        add(resources.getString(R.string.history_last_closed));
        add(lastClosed.getLast());
    }
    for (Database.HistoryEntry entity : MainApplication.getInstance().database.getHistory()) {
        while (entity.date < midnight) {
            if (current == 0) {
                current = 1;
                midnight -= 86400 * 1000;
            } else if (current == 1) {
                current = 2;
                midnight -= 86400 * 1000 * 6;
            } else {
                current = 3;
                midnight = 0;
            }
        }
        if (previous != current) {
            switch (current) {
                case 0:
                    add(resources.getString(R.string.history_today));
                    break;
                case 1:
                    add(resources.getString(R.string.history_yesterday));
                    break;
                case 2:
                    add(resources.getString(R.string.history_last_week));
                    break;
                case 3:
                    add(resources.getString(R.string.history_other));
                    break;
            }
            previous = current;
        }
        add(entity);
    }
    if (getCount() == 0) add(resources.getString(R.string.history_empty));
}
 
Example 18
Source File: ReviewFragment.java    From AnkiDroid-Wear with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Resources r = getResources();
    gestureButtonVelocity = r.getDisplayMetrics().heightPixels / GESTURE_BUTTON_ANIMATION_TIME_MS;
}
 
Example 19
Source File: BrainPhaserApplication.java    From BrainPhaser with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Licensed under CC BY-SA (c) 2012 Muhammad Nabeel Arif
 * http://stackoverflow.com/questions/4605527/converting-pixels-to-dp
 *
 * This method converts device specific pixels to density independent pixels.
 *
 * @param px A value in px (pixels) unit. Which we need to convert into dp
 * @return A float value to represent dp equivalent to px value
 */
public float convertPixelsToDp(float px){
    Resources resources = getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}
 
Example 20
Source File: Utils.java    From prayer-times-android with Apache License 2.0 2 votes vote down vote up
/**
 * This method converts dp unit to equivalent pixels, depending on device density.
 *
 * @param context Context to get resources and device specific display metrics
 * @param dp      A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(Context context, float dp) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}