下面列出了android.view.Display#getWidth ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
Log.d(TAG, "Screen resolution: " + screenResolution);
Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
// preview size is always something like 480*320, other 320*480
if (screenResolution.x < screenResolution.y) {
screenResolutionForCamera.x = screenResolution.y;
screenResolutionForCamera.y = screenResolution.x;
}
Log.i("#########", "screenX:" + screenResolutionForCamera.x + " screenY:" + screenResolutionForCamera.y);
cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
// cameraResolution = getCameraResolution(parameters, screenResolution);
Log.d(TAG, "Camera resolution: " + screenResolution);
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
Log.d(TAG, "Screen resolution: " + screenResolution);
Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
// preview size is always something like 480*320, other 320*480
if (screenResolution.x < screenResolution.y)
{
screenResolutionForCamera.x = screenResolution.y;
screenResolutionForCamera.y = screenResolution.x;
}
cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
Log.d(TAG, "Camera resolution: " + screenResolutionForCamera);
}
/**
* Sets the behind width.
*
* @param i The width the Sliding Menu will open to, in pixels
*/
@SuppressWarnings("deprecation")
public void setBehindWidth(int i) {
int width;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
try {
Class<?> cls = Display.class;
Class<?>[] parameterTypes = {Point.class};
Point parameter = new Point();
Method method = cls.getMethod("getSize", parameterTypes);
method.invoke(display, parameter);
width = parameter.x;
} catch (Exception e) {
width = display.getWidth();
}
setBehindOffset(width-i);
}
/**
* Sets the behind width.
*
* @param i The width the Sliding Menu will open to, in pixels
*/
@SuppressWarnings("deprecation")
public void setBehindWidth(int i) {
int width;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
try {
Class<?> cls = Display.class;
Class<?>[] parameterTypes = {Point.class};
Point parameter = new Point();
Method method = cls.getMethod("getSize", parameterTypes);
method.invoke(display, parameter);
width = parameter.x;
} catch (Exception e) {
width = display.getWidth();
}
setBehindOffset(width-i);
}
public void insertImage() {
// 1.构建Bitmap
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int w = display.getWidth();// w=480
int h = display.getHeight();// h=800
imageBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 最后一个参数叫位图结构
// ARGB--Alpha,Red,Green,Blue.
// ARGB为一种色彩模式,也就是RGB色彩模式附加上Alpha(透明度)通道,常见于32位位图的存储结构。
// 2.获取屏幕
View decorview = this.getWindow().getDecorView();// decor意思是装饰布置
decorview.setDrawingCacheEnabled(true);
imageBitmap = decorview.getDrawingCache();
PermissionUtil.getInstance().getPermission(PermissionConfig.Permission.ANDROID_PERMISSION_WRITE_EXTERNAL_STORAGE);
// saveBitmap(imageBitmap);
}
/**
* 获取屏幕截图
* @param activity 获取当前Activity
* @return 截图
*/
public static Bitmap shot(Activity activity) {
//获取window最底层的view
View view = activity.getWindow().getDecorView();
view.buildDrawingCache();
//状态栏高度
Rect rect = new Rect();
view.getWindowVisibleDisplayFrame(rect);
int stateBarHeight = rect.top;
Display display = activity.getWindowManager().getDefaultDisplay();
//获取屏幕宽高
int widths = display.getWidth();
int height = display.getHeight();
//设置允许当前窗口保存缓存信息
view.setDrawingCacheEnabled(true);
//去掉状态栏高度
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, stateBarHeight, widths, height - stateBarHeight);
view.destroyDrawingCache();
return bitmap;
}
/**
* 初始化操作,在Application的onCreate方法中初始化,建议在子线程中进行
*
* 添加的依赖:
compile 'com.facebook.fresco:fresco:0.12.0'
// 在 API < 14 上的机器支持 WebP 时,需要添加
compile 'com.facebook.fresco:animated-base-support:0.12.0'
// 支持 GIF 动图,需要添加
compile 'com.facebook.fresco:animated-gif:0.12.0'
// 支持 WebP (静态图+动图),需要添加
compile 'com.facebook.fresco:animated-webp:0.12.0'
compile 'com.facebook.fresco:webpsupport:0.12.0'
compile "com.facebook.fresco:imagepipeline-okhttp3:0.12.0+"
* @param context
* @param cacheSizeInM 磁盘缓存的大小,以M为单位
*/
public static void init(final Context context, int cacheSizeInM){
isWWW = true;
DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
.setMaxCacheSize(cacheSizeInM*1024*1024)
.setBaseDirectoryName(PHOTO_FRESCO)
.setBaseDirectoryPathSupplier(new Supplier<File>() {
@Override
public File get() {
return context.getCacheDir();
}
})
.build();
MyImageCacheStatsTracker imageCacheStatsTracker = new MyImageCacheStatsTracker();
OkHttpClient okHttpClient= getAllPassClient(context);
ImagePipelineConfig config = OkHttpImagePipelineConfigFactory.newBuilder(context,okHttpClient)
// ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context)
.setMainDiskCacheConfig(diskCacheConfig)
.setImageCacheStatsTracker(imageCacheStatsTracker)
.setDownsampleEnabled(true)//Downsampling,它处理图片的速度比常规的裁剪更快,
// 并且同时支持PNG,JPG以及WEP格式的图片,非常强大,与ResizeOptions配合使用
.setBitmapsConfig(Bitmap.Config.RGB_565)
.build();
Fresco.initialize(context, config);
WindowManager wm = (WindowManager) context.getSystemService(
Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenWidth = display.getWidth() - dip2px(context,15);
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
@SuppressWarnings("SuspiciousNameCombination")
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
// display.getSize(screenResolution);//api > 13
Log.d(TAG, "Screen resolution: " + screenResolution);
//-- modify by ydcool at 2015-11-18 16:12:15 --
Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
// preview size is always something like 480*320, other 320*480
if (screenResolution.x < screenResolution.y) {
screenResolutionForCamera.x = screenResolution.y;
screenResolutionForCamera.y = screenResolution.x;
}
// cameraResolution = getCameraResolution(parameters, screenResolution);
cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
//-- end modify --
Log.d(TAG, "Camera resolution: " + screenResolution);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Display display =getActivity().getWindowManager().getDefaultDisplay();
dims = new int[] { display.getWidth(), display.getHeight() };
}
@SuppressWarnings("deprecation")
public static void setScreenDimensions() {
Display display = c.getWindow().getWindowManager().getDefaultDisplay();
screen_w = display.getWidth();
screen_h = display.getHeight();
screen_s = (screen_h > screen_w) ? screen_w : screen_h;
if (!settings.getString(
res.getString(R.string.fullscreen),
res.getString(R.string.fullscreenDefault)
).equals("1")) {
screen_h -= statusBarHeight;
}
int screen_size = c.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
if (screen_size == 4) { //Configuration.SCREENLAYOUT_SIZE_XLARGE) {
tablet = true;
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.HONEYCOMB) {
screen_h -= 48; // TODO - hardcoded menu height for Honeycomb bug
}
}
if (tablet) {
button_w = (int)(screen_s / 5.5);
} else {
button_w = (int)(screen_s / 4.5);
}
button_h = button_w;
health_bar_h = Tools.scale(7 + 17 + 17); // margin + height * 2, one margin less than GUIGame's HP bar
screen_r =
(screen_h > screen_w) ?
(screen_w - health_bar_h - button_w) / 2 :
(screen_h - health_bar_h - button_h) / 2;
}
/**
* Compute what the width and height of a single tile should be, based upon the available
* screen space, how many columns there should be, and how many rows we want to show at a time.
* Round up to the nearest integer since the GridView's width and height will ultimately be
* computed indirectly from these values, and those values need to be integers, and we don't
* want to end up cutting things off
*/
private Pair<Integer, Integer> computeTileWidthAndHeight(Context context) {
double screenWidth, screenHeight;
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
} else {
screenWidth = display.getWidth();
screenHeight = display.getHeight();
}
if (!tileBeingShownInGridView()) {
// If we added padding, subtract that space since we can't use it
screenWidth = screenWidth - DEFAULT_TILE_PADDING_HORIZONTAL * 2;
}
int tileHeight;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (beingDisplayedInAwesomeMode) {
// if in awesome mode, split available width in half
screenWidth = screenWidth / 2;
}
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(false, screenHeight));
} else {
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(true, screenHeight));
}
int tileWidth = (int)Math.ceil(screenWidth / numTilesPerRow);
return new Pair<>(tileWidth, tileHeight);
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
// We're landscape-only, and have apparently seen issues with display
// thinking it's portrait
// when waking from sleep. If it's not landscape, assume it's mistaken
// and reverse them:
if (width < height) {
if(AppConfig.DEBUG){
Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect");
}
int temp = width;
width = height;
height = temp;
}
screenResolution = new Point(height, width);
if(AppConfig.DEBUG){
Log.i(TAG, "Screen resolution: " + screenResolution);
}
cameraResolution = findBestPreviewSizeValue(parameters, new Point(width, height), false);
if(AppConfig.DEBUG){
Log.i(TAG, "Camera resolution: " + cameraResolution);
}
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private Point getDisplaySize(final Display display) {
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) {
point.x = display.getWidth();
point.y = display.getHeight();
}
return point;
}
/**
* Get the size of current screen.
*
* @param context the context
* @return the size
*/
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public static Point getScreenSize(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
return new Point(display.getWidth(), display.getHeight());
} else {
Point point = new Point();
display.getSize(point);
return point;
}
}
public static Point getScreenSize(Context context){
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point out = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(out);
}else{
int width = display.getWidth();
int height = display.getHeight();
out.set(width, height);
}
return out;
}
public static Point getScreenHeightWidth(WindowManager mWindowManager) {
Point point = new Point();
try {
Display display = mWindowManager.getDefaultDisplay();
if (VERSION.SDK_INT >= 17) {
display.getRealSize(point);
} else {
point.y = display.getHeight();
point.x = display.getWidth();
}
} catch (Throwable e) {
LOG.w(TAG, "getScreenHeightWidth failed(Throwable): " + e.getMessage());
}
return point;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// go fullscreen for devices with QVGA screen (only way I found
// how to fit UI on the screen)
Display display = getWindowManager().getDefaultDisplay();
if ((display.getWidth() == 240 || display.getWidth() == 320)
&& (display.getHeight() == 240 || display.getHeight() == 320)) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mFullScreen = true;
}
setContentView(R.layout.sudoku_edit);
mRootLayout = findViewById(R.id.root_layout);
SudokuBoardView mBoard = findViewById(R.id.sudoku_board);
mDatabase = new SudokuDatabase(getApplicationContext());
mGuiHandler = new Handler();
Intent intent = getIntent();
String action = intent.getAction();
long mSudokuID;
if (Intent.ACTION_EDIT.equals(action)) {
// Requested to edit: set that state, and the data being edited.
mState = STATE_EDIT;
if (intent.hasExtra(EXTRA_SUDOKU_ID)) {
mSudokuID = intent.getLongExtra(EXTRA_SUDOKU_ID, 0);
} else {
throw new IllegalArgumentException(String.format("Extra with key '%s' is required.", EXTRA_SUDOKU_ID));
}
} else if (Intent.ACTION_INSERT.equals(action)) {
mState = STATE_INSERT;
mSudokuID = 0;
if (intent.hasExtra(EXTRA_FOLDER_ID)) {
mFolderID = intent.getLongExtra(EXTRA_FOLDER_ID, 0);
} else {
throw new IllegalArgumentException(String.format("Extra with key '%s' is required.", EXTRA_FOLDER_ID));
}
} else {
// Whoops, unknown action! Bail.
Log.e(TAG, "Unknown action, exiting.");
finish();
return;
}
if (savedInstanceState != null) {
mGame = new SudokuGame();
mGame.restoreState(savedInstanceState);
} else {
if (mSudokuID != 0) {
// existing sudoku, read it from database
mGame = mDatabase.getSudoku(mSudokuID);
mGame.getCells().markAllCellsAsEditable();
} else {
mGame = SudokuGame.createEmptyGame();
}
}
mBoard.setGame(mGame);
IMControlPanel mInputMethods = findViewById(R.id.input_methods);
mInputMethods.initialize(mBoard, mGame, null);
// only numpad input method will be enabled
for (InputMethod im : mInputMethods.getInputMethods()) {
im.setEnabled(false);
}
mInputMethods.getInputMethod(IMControlPanel.INPUT_METHOD_NUMPAD).setEnabled(true);
mInputMethods.activateInputMethod(IMControlPanel.INPUT_METHOD_NUMPAD);
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static void lockOrientation(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
int rotation = display.getRotation();
int height;
int width;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
height = display.getHeight();
width = display.getWidth();
} else {
Point size = new Point();
display.getSize(size);
height = size.y;
width = size.x;
}
switch (rotation) {
case Surface.ROTATION_90:
if (width > height)
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case Surface.ROTATION_180:
if (height > width)
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
else
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case Surface.ROTATION_270:
if (width > height)
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
else
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
default:
if (height > width)
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
@Override
protected void onResume() {
super.onResume();
// This assumes the view is full screen, which is a good assumption
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 7 / 8;
Intent intent = getIntent();
if (intent == null) {
return;
}
try {
boolean useVCard = intent.getBooleanExtra(USE_VCARD_KEY, false);
qrCodeEncoder = new QRCodeEncoder(this, intent, smallerDimension, useVCard);
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
if (bitmap == null) {
Log.w(TAG, "Could not encode barcode");
showErrorMessage(fakeR.getId("string", "msg_encode_contents_failed"));
qrCodeEncoder = null;
return;
}
ImageView view = (ImageView) findViewById(fakeR.getId("id", "image_view"));
view.setImageBitmap(bitmap);
TextView contents = (TextView) findViewById(fakeR.getId("id", "contents_text_view"));
if (intent.getBooleanExtra(Intents.Encode.SHOW_CONTENTS, true)) {
contents.setText(qrCodeEncoder.getDisplayContents());
setTitle(qrCodeEncoder.getTitle());
} else {
contents.setText("");
setTitle("");
}
} catch (WriterException e) {
Log.w(TAG, "Could not encode barcode", e);
showErrorMessage(fakeR.getId("string", "msg_encode_contents_failed"));
qrCodeEncoder = null;
}
}
private int getScreenWidth() {
Display display = ((WindowManager)this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
return display.getWidth();
}