下面列出了怎么用android.graphics.Rect的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
int previewFormat = configManager.getPreviewFormat();
String previewFormatString = configManager.getPreviewFormatString();
switch (previewFormat) {
// This is the standard Android format which all devices are REQUIRED to support.
// In theory, it's the only one we should ever care about.
case ImageFormat.NV21:
// This format has never been seen in the wild, but is compatible as we only care
// about the Y channel, so allow it.
case ImageFormat.NV16:
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
default:
// The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
// Fortunately, it too has all the Y data up front, so we can read it.
if ("yuv420p".equals(previewFormatString)) {
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
}
}
throw new IllegalArgumentException("Unsupported picture format: " +
previewFormat + '/' + previewFormatString);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if(parent.getChildAdapterPosition(view) == 0) {
if(orientation == SnappingRecyclerView.VERTICAL) {
outRect.top = (parent.getHeight() / 2) - (view.getHeight() / 2);
} else {
outRect.left = (parent.getWidth() / 2) - (view.getWidth() / 2);
}
} else if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
if(orientation == SnappingRecyclerView.VERTICAL) {
outRect.bottom = (parent.getHeight() / 2) - (view.getHeight() / 2);
} else {
outRect.right = (parent.getWidth() / 2) - (view.getWidth() / 2);
}
}
}
void handleMotion(int edge, float dx, float dy) {
Rect r = computeLayout();
if (edge == MOVE) {
// Convert to image space before sending to moveBy()
moveBy(dx * (cropRect.width() / r.width()),
dy * (cropRect.height() / r.height()));
} else {
if (((GROW_LEFT_EDGE | GROW_RIGHT_EDGE) & edge) == 0) {
dx = 0;
}
if (((GROW_TOP_EDGE | GROW_BOTTOM_EDGE) & edge) == 0) {
dy = 0;
}
// Convert to image space before sending to growBy()
float xDelta = dx * (cropRect.width() / r.width());
float yDelta = dy * (cropRect.height() / r.height());
growBy((((edge & GROW_LEFT_EDGE) != 0) ? -1 : 1) * xDelta,
(((edge & GROW_TOP_EDGE) != 0) ? -1 : 1) * yDelta);
}
}
private static Bitmap createDrawableBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
if (width <= 0 || height <= 0) {
return null;
}
float scale = Math.min(1.0f, ((float) MAX_IMAGE_SIZE) / ((float) (width * height)));
if ((drawable instanceof BitmapDrawable) && scale == 1.0f) {
return ((BitmapDrawable) drawable).getBitmap();
}
int bitmapWidth = (int) (((float) width) * scale);
int bitmapHeight = (int) (((float) height) * scale);
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Rect existingBounds = drawable.getBounds();
int left = existingBounds.left;
int top = existingBounds.top;
int right = existingBounds.right;
int bottom = existingBounds.bottom;
drawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
drawable.draw(canvas);
drawable.setBounds(left, top, right, bottom);
return bitmap;
}
@Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
int radius = Math.min(bounds.width(), bounds.height()) / 2;
int cx = bounds.centerX();
int cy = bounds.centerY();
Paint paint = this.paint;
paint.setColor(background);
canvas.drawCircle(cx, cy, radius * 1f, paint);
if (accent != primary && accent != Color.TRANSPARENT) {
RectF rectF = this.rectF;
applyRectRadius(rectF, cx, cy, radius * 0.8f);
paint.setColor(accent);
canvas.drawArc(rectF, -20, 130, true, paint);
paint.setColor(background);
canvas.drawCircle(cx, cy, radius * 0.7f, paint);
paint.setColor(primary);
canvas.drawCircle(cx, cy, radius * 0.65f, paint);
canvas.drawArc(rectF, 114, 222, true, paint);
} else {
paint.setColor(primary);
canvas.drawCircle(cx, cy, radius * 0.8f, paint);
}
}
/**
* 截屏,只能截取当前屏幕显示的区域,不包含status bar
*/
public static Bitmap screenShot(Activity activity){
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 获取状态栏高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 获取屏幕长和高
int width = CommonUtils.getScreenWidth();
int height = CommonUtils.getScreenHeight();
// 去掉标题栏
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
/**
* Creates a {@link LayoutManager} instance.
* @param host A {@link LayoutManagerHost} instance.
*/
public LayoutManager(LayoutManagerHost host) {
mHost = host;
mPxToDp = 1.f / mHost.getContext().getResources().getDisplayMetrics().density;
mSceneChangeObservers = new ObserverList<SceneChangeObserver>();
int hostWidth = host.getWidth();
int hostHeight = host.getHeight();
mLastViewportPx.set(0, 0, hostWidth, hostHeight);
mLastVisibleViewportPx.set(0, 0, hostWidth, hostHeight);
mLastFullscreenViewportPx.set(0, 0, hostWidth, hostHeight);
mLastContentWidthDp = hostWidth * mPxToDp;
mLastContentHeightDp = hostHeight * mPxToDp;
mLastViewportDp.set(0, 0, mLastContentWidthDp, mLastContentHeightDp);
mLastVisibleViewportDp.set(0, 0, mLastContentWidthDp, mLastContentHeightDp);
mLastFullscreenViewportDp.set(0, 0, mLastContentWidthDp, mLastContentHeightDp);
mCachedVisibleViewport = new Rect();
mLastHeightMinusBrowserControlsDp = mLastContentHeightDp;
}
/**
* close surface
* @param smooth smoothly or not.
* @param notify if notify all the listeners.
*/
public void close(boolean smooth, boolean notify){
ViewGroup surface = getSurfaceView();
int dx, dy;
if(smooth)
mDragHelper.smoothSlideViewTo(getSurfaceView(), getPaddingLeft(), getPaddingTop());
else {
Rect rect = computeSurfaceLayoutArea(false);
dx = rect.left - surface.getLeft();
dy = rect.top - surface.getTop();
surface.layout(rect.left, rect.top, rect.right, rect.bottom);
if(notify) {
dispatchRevealEvent(rect.left, rect.top, rect.right, rect.bottom);
dispatchSwipeEvent(rect.left, rect.top, dx, dy);
}else{
safeBottomView();
}
}
invalidate();
}
private void drawStaticFocus(Canvas paramCanvas) {
float f1 = this.mScaleXValue - 1.0F;
float f2 = this.mScaleYValue - 1.0F;
int i = this.mFrameRate;
int j = this.mCurrentFrame;
float f3 = 1.0F + f1 * j / i;
float f4 = 1.0F + f2 * j / i;
Rect localRect = getDstRectAfterScale(true);
if (null == localRect) {
return;
}
this.mFocusRect = localRect;
this.mCurrentRect = localRect;
if (isLastFrame()) {
this.mMySelectedDrawableShadow.setBounds(localRect);
this.mMySelectedDrawableShadow.draw(paramCanvas);
this.mMySelectedDrawableShadow.setVisible(true, true);
} else {
this.mMySelectedDrawable.setBounds(localRect);
this.mMySelectedDrawable.draw(paramCanvas);
this.mMySelectedDrawable.setVisible(true, true);
}
if ((this.mSelectedView != null) && (paramCanvas != null) && ((this.mState == 0) || (isLastFrame()))) {
drawChild(paramCanvas);
}
}
private ContrastSwatch(Parcel source) {
mBackgroundColors = new LinkedList<Integer>();
mForegroundColors = new LinkedList<Integer>();
mLuminanceMap = new HashMap<Integer, Double>();
mLuminanceHistogram = new HashMap<Double, Integer>();
mName = source.readString();
source.readMap(mLuminanceMap, null);
source.readMap(mLuminanceHistogram, null);
source.readList(mBackgroundColors, null);
source.readList(mForegroundColors, null);
mBackgroundLuminance = source.readDouble();
mForegroundLuminance = source.readDouble();
mScreenBounds = (Rect) source.readValue(Rect.class.getClassLoader());
mContrastRatio = source.readDouble();
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
/**
* Draws a black border over the screenshot of the view passed in.
*/
protected Bitmap getBitmapWithBorder(View v)
{
Bitmap bitmap = getBitmapFromView(v);
Canvas canvas = new Canvas(bitmap);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(LINE_THICKNESS);
int accentColor = ControlHelper.getColor(getContext(), R.attr.colorAccent);
paint.setColor(accentColor);
canvas.drawRect(rect, paint);
return bitmap;
}
@TargetApi(Build.VERSION_CODES.M)
public Bundle getActivityLaunchOptions(View v) {
if (AndroidVersion.isAtLeastMarshmallow) {
int left = 0, top = 0;
int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
if (v instanceof TextView) {
// Launch from center of icon, not entire view
Drawable icon = Workspace.getTextViewIcon((TextView) v);
if (icon != null) {
Rect bounds = icon.getBounds();
left = (width - bounds.width()) / 2;
top = v.getPaddingTop();
width = bounds.width();
height = bounds.height();
}
}
return ActivityOptions.makeClipRevealAnimation(v, left, top, width, height).toBundle();
} else if (AndroidVersion.isAtLeastLollipopMR1) {
// On L devices, we use the device default slide-up transition.
// On L MR1 devices, we use a custom version of the slide-up transition which
// doesn't have the delay present in the device default.
return ActivityOptions.makeCustomAnimation(
this, R.anim.task_open_enter, R.anim.no_anim).toBundle();
}
return null;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
* not UI / screen.
*/
public Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect rect = new Rect(getFramingRect());
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
//modify here
// rect.left = rect.left * cameraResolution.x / screenResolution.x;
// rect.right = rect.right * cameraResolution.x / screenResolution.x;
// rect.top = rect.top * cameraResolution.y / screenResolution.y;
// rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
framingRectInPreview = rect;
}
return framingRectInPreview;
}
private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint,
final Rect dirtyRect) {
// Clear previous dirty rectangle.
if (!dirtyRect.isEmpty()) {
paint.setColor(Color.TRANSPARENT);
paint.setStyle(Paint.Style.FILL);
offscreenCanvas.drawRect(dirtyRect, paint);
}
dirtyRect.setEmpty();
boolean needsUpdatingGestureTrail = false;
// Draw gesture trails to offscreen buffer.
synchronized (mGestureTrails) {
// Trails count == fingers count that have ever been active.
final int trailsCount = mGestureTrails.size();
for (int index = 0; index < trailsCount; index++) {
final GestureTrailDrawingPoints trail = mGestureTrails.valueAt(index);
needsUpdatingGestureTrail |= trail.drawGestureTrail(offscreenCanvas, paint,
mGestureTrailBoundsRect, mDrawingParams);
// {@link #mGestureTrailBoundsRect} has bounding box of the trail.
dirtyRect.union(mGestureTrailBoundsRect);
}
}
return needsUpdatingGestureTrail;
}
@Override protected final boolean fitSystemWindows(@NonNull Rect insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Intentionally do not modify the bottom inset. For some reason,
// if the bottom inset is modified, window resizing stops working.
// TODO: Figure out why.
mInsets[0] = insets.left;
mInsets[1] = insets.top;
mInsets[2] = insets.right;
insets.left = 0;
insets.top = 0;
insets.right = 0;
}
return super.fitSystemWindows(insets);
}
/**
* Allows third party apps to specify the scanning rectangle dimensions, rather than determine
* them automatically based on screen resolution.
*
* @param width The width in pixels to scan.
* @param height The height in pixels to scan.
*/
public synchronized void setManualFramingRect(int width, int height) {
if (initialized) {
Point screenResolution = configManager.getScreenResolution();
if (width > screenResolution.x) {
width = screenResolution.x;
}
if (height > screenResolution.y) {
height = screenResolution.y;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.d(TAG, "Calculated manual framing rect: " + framingRect);
framingRectInPreview = null;
} else {
requestedFramingRectWidth = width;
requestedFramingRectHeight = height;
}
}
/**
* Calculate the bounds for UrlViewport and set them to out rect.
*/
private void updateUrlViewportBounds(Rect out, VisualState visualState,
boolean ignoreTranslationY) {
// Calculate the visible boundaries of the left and right most child views
// of the location bar.
int leftViewPosition = (int) MathUtils.interpolate(
getViewBoundsLeftOfLocationBar(visualState), 0f, mUrlExpansionPercent)
- mUrlBackgroundPadding.left;
int rightViewPosition = (int) MathUtils.interpolate(
getViewBoundsRightOfLocationBar(visualState), getWidth(), mUrlExpansionPercent)
+ mUrlBackgroundPadding.right;
// The bounds are set by the following:
// - The left most visible location bar child view.
// - The top of the viewport is aligned with the top of the location bar.
// - The right most visible location bar child view.
// - The bottom of the viewport is aligned with the bottom of the location bar.
// Additional padding can be applied for use during animations.
float yOffset = ignoreTranslationY ? mPhoneLocationBar.getTop() : mPhoneLocationBar.getY();
out.set(leftViewPosition,
(int) (yOffset - (mUrlBackgroundPadding.top * mUrlExpansionPercent)),
rightViewPosition,
(int) (yOffset + MathUtils.interpolate(mPhoneLocationBar.getMeasuredHeight(),
getHeight() + mUrlBackgroundPadding.bottom, mUrlExpansionPercent)));
}
private void drawStage2(Canvas canvas, float progress) {
final Rect bounds = getBounds();
progress = interpolator.getInterpolation(progress);
tempRect.left = (int) (AndroidUtilities.dp(2) * scaleX);
tempRect.bottom = bounds.bottom - ((int) (AndroidUtilities.dp(6) * scaleY));
tempRect.right = bounds.right - tempRect.left;
tempRect.top = tempRect.bottom - ((int) (AndroidUtilities.dp(4) * scaleY));
tempRect.offset(0, AndroidUtilities.dp(AndroidUtilities.lerp(0, -8, progress)));
secondaryRectDrawable.setBounds(tempRect);
secondaryRectDrawable.draw(canvas);
tempRect.left = (int) (AndroidUtilities.dpf2(AndroidUtilities.lerp(1, 2, progress)) * scaleX);
tempRect.top = (int) (AndroidUtilities.dpf2(AndroidUtilities.lerp(5, 6, progress)) * scaleY);
tempRect.right = bounds.right - tempRect.left;
tempRect.bottom = tempRect.top + (int) (AndroidUtilities.dpf2(AndroidUtilities.lerp(6, 4, progress)) * scaleY);
tempRect.offset(0, AndroidUtilities.dp(AndroidUtilities.lerp(0, 8, progress)));
primaryRectDrawable.setBounds(tempRect);
primaryRectDrawable.setAlpha(255);
primaryRectDrawable.draw(canvas);
}
private SlideDrawable(ActionBarDrawerToggle actionBarDrawerToggle, Drawable wrapped) {
boolean z = false;
this.this$0 = actionBarDrawerToggle;
super(wrapped, 0);
if (VERSION.SDK_INT > 18) {
z = true;
}
this.mHasMirroring = z;
this.mTmpRect = new Rect();
}
static boolean sameSize(final LayoutOutput nextOutput, final LayoutOutput currentOutput) {
final Rect nextBounds = nextOutput.getBounds();
final Rect currentBounds = currentOutput.getBounds();
return nextBounds.width() == currentBounds.width()
&& nextBounds.height() == currentBounds.height();
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0;
increment = 1;
end = count;
} else {
index = count - 1;
increment = -1;
end = -1;
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true;
}
}
}
}
return false;
}
@OnBoundsDefined
static void onBoundsDefined(
ComponentContext c, ComponentLayout layout, Output<Rect> viewportDimensions) {
final int width = layout.getWidth();
final int height = layout.getHeight();
int paddingX = 0, paddingY = 0;
if (layout.isPaddingSet()) {
paddingX = layout.getPaddingLeft() + layout.getPaddingRight();
paddingY = layout.getPaddingTop() + layout.getPaddingBottom();
}
viewportDimensions.set(new Rect(0, 0, width - paddingX, height - paddingY));
}
@Test
public void testResizeRect_correctSize() {
Rect testRect = new Rect(0, 0, 48, 48);
Rect expected = new Rect(0, 0, 48, 48);
AccessibilityUtils.resizeRect(48, testRect);
assertTrue(testRect.equals(expected));
}
/**
* @since 6.0.0
*/
public Projection(
final double pZoomLevel, final Rect pScreenRect,
final GeoPoint pCenter,
final long pScrollX, final long pScrollY,
final float pOrientation,
final boolean pHorizontalWrapEnabled, final boolean pVerticalWrapEnabled,
final TileSystem pTileSystem,
final int pMapCenterOffsetX, final int pMapCenterOffsetY) {
mMapCenterOffsetX = pMapCenterOffsetX;
mMapCenterOffsetY = pMapCenterOffsetY;
mZoomLevelProjection = pZoomLevel;
horizontalWrapEnabled = pHorizontalWrapEnabled;
verticalWrapEnabled = pVerticalWrapEnabled;
mTileSystem = pTileSystem;
mMercatorMapSize = TileSystem.MapSize(mZoomLevelProjection);
mTileSize = TileSystem.getTileSize(mZoomLevelProjection);
mIntrinsicScreenRectProjection = pScreenRect;
final GeoPoint center = pCenter != null ? pCenter : new GeoPoint(0., 0);
mScrollX = pScrollX;
mScrollY = pScrollY;
mOffsetX = getScreenCenterX() - mScrollX - mTileSystem.getMercatorXFromLongitude(center.getLongitude(), mMercatorMapSize, this.horizontalWrapEnabled);
mOffsetY = getScreenCenterY() - mScrollY - mTileSystem.getMercatorYFromLatitude(center.getLatitude(), mMercatorMapSize, this.verticalWrapEnabled);
mOrientation = pOrientation;
mRotateAndScaleMatrix.preRotate(mOrientation, getScreenCenterX(), getScreenCenterY());
mRotateAndScaleMatrix.invert(mUnrotateAndScaleMatrix);
refresh();
}
private Rect traitsListItemLocation(int item, int adjust) {
View v = traitList.getChildAt(item);
final int[] location = new int[2];
v.getLocationOnScreen(location);
Rect droidTarget = new Rect(location[0], location[1], location[0] + v.getWidth()/adjust, location[1] + v.getHeight());
return droidTarget;
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (focused)
mFormatBar.setEditText(this);
else
mFormatBar.setEditText(null);
}
private Rect computeBottomLayoutAreaViaSurface(ShowMode mode,
Rect surfaceArea) {
Rect rect = surfaceArea;
int bl = rect.left, bt = rect.top, br = rect.right, bb = rect.bottom;
if (mode == ShowMode.PullOut) {
if (mDragEdge == DragEdge.Left)
bl = rect.left - mDragDistance;
else if (mDragEdge == DragEdge.Right)
bl = rect.right;
else if (mDragEdge == DragEdge.Top)
bt = rect.top - mDragDistance;
else
bt = rect.bottom;
if (mDragEdge == DragEdge.Left || mDragEdge == DragEdge.Right) {
bb = rect.bottom;
br = bl + getBottomView().getMeasuredWidth();
} else {
bb = bt + getBottomView().getMeasuredHeight();
br = rect.right;
}
} else if (mode == ShowMode.LayDown) {
if (mDragEdge == DragEdge.Left)
br = bl + mDragDistance;
else if (mDragEdge == DragEdge.Right)
bl = br - mDragDistance;
else if (mDragEdge == DragEdge.Top)
bb = bt + mDragDistance;
else
bt = bb - mDragDistance;
}
return new Rect(bl, bt, br, bb);
}
@Override
public void getFocusedRect(@Nullable Rect r) {
super.getFocusedRect(r);
TextInputLayout textInputLayout = getTextInputLayout();
if (textInputLayout != null
&& textInputLayoutFocusedRectEnabled
&& r != null) {
textInputLayout.getFocusedRect(parentRect);
r.bottom = parentRect.bottom;
}
}