下面列出了怎么用android.graphics.Canvas的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int measuredHeight = getMeasuredHeight();
float x = (getRight() - getLeft()) / 2;
float y = (getBottom() - getTop()) / 2 + textHeight / 2;
int currentValueStart = (int) (y + currentScrollOffset);
int prevValueStart = currentValueStart - measuredHeight;
int nextValueStart = currentValueStart + measuredHeight;
canvas.drawText(getValue(currentValueOffset + 1) + "", x, prevValueStart, textPaint);
canvas.drawText(getValue(currentValueOffset) + "", x, currentValueStart, textPaint);
canvas.drawText(getValue(currentValueOffset - 1) + "", x, nextValueStart, textPaint);
}
public final synchronized boolean draw(Canvas canvas, float left, float top, Paint paint) {
boolean z = true;
synchronized (this) {
if (this.bitmapArray != null) {
for (int i = 0; i < this.bitmapArray.length; i++) {
for (int j = 0; j < this.bitmapArray[i].length; j++) {
Bitmap bmp = this.bitmapArray[i][j];
if (bmp != null) {
float dleft = left + ((float) (bmp.getWidth() * j));
if (dleft <= ((float) canvas.getWidth()) && ((float) bmp.getWidth()) + dleft >= 0.0f) {
float dtop = top + ((float) (bmp.getHeight() * i));
if (dtop <= ((float) canvas.getHeight()) && ((float) bmp.getHeight()) + dtop >= 0.0f) {
canvas.drawBitmap(bmp, dleft, dtop, paint);
}
}
}
}
}
} else if (this.bitmap != null) {
canvas.drawBitmap(this.bitmap, left, top, paint);
} else {
z = false;
}
}
return z;
}
/** Draw dividers to the right of each child view */
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params =
(RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getRight() + params.rightMargin + mInsets;
final int right = left + mDivider.getIntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
/**
* 绘制间隔
*/
private void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin +
Math.round(ViewCompat.getTranslationY(child));
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {
Bitmap source = resource.get();
int width = source.getWidth();
int height = source.getHeight();
Bitmap.Config config =
source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888;
Bitmap bitmap = mBitmapPool.get(width, height, config);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(width, height, config);
}
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColorFilter(new PorterDuffColorFilter(mColor, PorterDuff.Mode.SRC_ATOP));
canvas.drawBitmap(source, 0, 0, paint);
return BitmapResource.obtain(bitmap, mBitmapPool);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("zdy", "......" + getWidth() + " " + getHeight());
if (getWidth() != 0) {
int count = this.textArr.length;
Paint p = new Paint();
p.setColor(this.lineColor);
p.setStyle(Style.FILL);
float with = (((float) getWidth()) * 1.0f) / ((float) this.textArr.length);
for (int i = 1; i < count; i++) {
RectF r1 = new RectF();
float nPos = with * ((float) i);
r1.left = nPos - (((float) this.space) / 2.0f);
r1.right = (((float) this.space) / 2.0f) + nPos;
r1.top = (float) (this.lineStroke + 0);
r1.bottom = (float) (getHeight() - this.lineStroke);
canvas.drawRect(r1, p);
}
}
}
/**
* 画折线
*
* @param canvas
*/
public void drawLines(Canvas canvas, Line line) {
if (line != null && isShow) {
linePaint.setColor(line.getLineColor());
linePaint.setStrokeWidth(LeafUtil.dp2px(mContext, line.getLineWidth()));
linePaint.setStyle(Paint.Style.STROKE);
List<PointValue> values = line.getValues();
Path path = line.getPath();
int size = values.size();
for (int i = 0; i < size; i++) {
PointValue point = values.get(i);
if (i == 0) path.moveTo(point.getOriginX(), point.getOriginY());
else path.lineTo(point.getOriginX(), point.getOriginY());
}
measure = new PathMeasure(path, false);
linePaint.setPathEffect(createPathEffect(measure.getLength(), phase, 0.0f));
canvas.drawPath(path, linePaint);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap == null) {
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(mWidth / 2, mWidth / 2, mCircleRadius, mPaint);
} else {
if (isChecked()) {
mPaint.setColor(mColorChecked);
if (mBackgroundChecked != null)
mBitmap = Bitmap.createScaledBitmap(mBackgroundChecked, mCircleRadius, mCircleRadius, true);
} else {
mPaint.setColor(mColorNormal);
if (mBackground != null)
mBitmap = Bitmap.createScaledBitmap(mBackground, mCircleRadius, mCircleRadius, true);
}
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(mWidth / 2, mWidth / 2, mCircleRadius, mPaint);
canvas.drawBitmap(mBitmap, mCircleRadius + mMargin - mBitmap.getWidth() / 2, mCircleRadius + mMargin - mBitmap.getHeight() / 2, mPaint);
}
}
@Override
public void draw(Canvas c, MapView mapView, boolean shadow) {
if (mFocusChanged) {
mFocusChanged = false;
// Remove any current focus
if (mPopupView != null)
mapView.removeView(mPopupView);
SampleOverlayItem item = this.getFocus();
if (item != null) {
mPopupView = getPopupView(mapView.getContext(), item);
MapView.LayoutParams lp = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, item.getPoint(),
MapView.LayoutParams.TOP_CENTER, 0, 0);
mapView.addView(mPopupView, lp);
}
}
super.draw(c, mapView, shadow);
}
@Override
protected void onDraw(Canvas canvas) {
if (mIfDrawText) {
calculateDrawRectF();
} else {
calculateDrawRectFWithoutProgressText();
}
if (mDrawReachedBar) {
canvas.drawRect(mReachedRectF, mReachedBarPaint);
}
if (mDrawUnreachedBar) {
canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);
}
if (mIfDrawText) canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint);
}
public static Bitmap getRoundedCornerBitmap(Bitmap input,
float cornerRadius, int w, int h) {
Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(input, 0, 0, paint);
return output;
}
@Override
protected void onDraw(Canvas canvas) {
if (currentAction == ACTION_DELETE || currentAction == ACTION_CLEAR) {
int newSeconds = timeLeft > 0 ? (int) Math.ceil(timeLeft / 1000.0f) : 0;
if (prevSeconds != newSeconds) {
prevSeconds = newSeconds;
timeLeftString = String.format("%d", Math.max(1, newSeconds));
textWidth = (int) Math.ceil(textPaint.measureText(timeLeftString));
}
canvas.drawText(timeLeftString, rect.centerX() - textWidth / 2, AndroidUtilities.dp(28.2f), textPaint);
canvas.drawArc(rect, -90, -360 * (timeLeft / 5000.0f), false, progressPaint);
}
long newTime = SystemClock.elapsedRealtime();
long dt = newTime - lastUpdateTime;
timeLeft -= dt;
lastUpdateTime = newTime;
if (timeLeft <= 0) {
hide(true, 1);
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas)
{
canvas.save();
//旋转
canvas.rotate(mRotateAngle, getViewCenterX(), getViewCenterY());
//路径
createStarPath(mStarPath, 5, -18);
//路径加入中心圆
mStarPath.addCircle(getViewCenterX(), getViewCenterY(), mCenterCircleR, Path.Direction.CW);
//这个很关键,选择路径填充方式
mStarPath.setFillType(Path.FillType.EVEN_ODD);
//绘制
canvas.drawPath(mStarPath, mFullPaint);
canvas.restore();
}
/**
* Drawing only virtical lines in Android
*/
private void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void draw(Canvas canvas) {
canvas.drawCircle(mBounds.centerX(), mBounds.centerY(), mBounds.centerX(), mBackgroundPaint);
Picture picture = new Picture() ;
picture.draw(canvas);
canvas.save();
canvas.rotate(180 * mRotation, (x(0) + x(1))/2, (y(0) + y(1))/2);
canvas.drawLine(x(0), y(0), x(1), y(1), mLinePaint);
canvas.restore();
canvas.save();
canvas.rotate(180 * mRotation, (x(2) + x(3)) / 2, (y(2) + y(3)) / 2);
canvas.drawLine(x(2), y(2), x(3), y(3), mLinePaint);
canvas.restore();
canvas.save();
canvas.rotate(180 * mRotation, (x(4) + x(5)) / 2, (y(4) + y(5)) / 2);
canvas.drawLine(x(4), y(4), x(5), y(5), mLinePaint);
canvas.restore();
}
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
if(topDown){
canvas.translate(getWidth(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
return;
}
if (mFillColor != Color.TRANSPARENT) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mFillPaint);
}
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mBorderRadius, mBorderPaint);
}
}
/**
* This method draws dimmed area around the crop bounds.
*
* @param canvas - valid canvas object
*/
protected void drawDimmedLayer(@NonNull Canvas canvas) {
canvas.save();
if (mCircleDimmedLayer) {
canvas.clipPath(mCircularPath, Region.Op.DIFFERENCE);
} else {
canvas.clipRect(mCropViewRect, Region.Op.DIFFERENCE);
}
canvas.drawColor(mDimmedColor);
canvas.restore();
if (mCircleDimmedLayer) { // Draw 1px stroke to fix antialias
canvas.drawCircle(mCropViewRect.centerX(), mCropViewRect.centerY(),
Math.min(mCropViewRect.width(), mCropViewRect.height()) / 2.f, mDimmedStrokePaint);
}
}
public void draw(Canvas c) {
Drawable shadowDrawable;
super.draw(c);
if (isLayoutRtlSupport()) {
shadowDrawable = this.mShadowDrawableRight;
} else {
shadowDrawable = this.mShadowDrawableLeft;
}
View shadowView = getChildCount() > 1 ? getChildAt(1) : null;
if (shadowView != null && shadowDrawable != null) {
int left;
int right;
int top = shadowView.getTop();
int bottom = shadowView.getBottom();
int shadowWidth = shadowDrawable.getIntrinsicWidth();
if (isLayoutRtlSupport()) {
left = shadowView.getRight();
right = left + shadowWidth;
} else {
right = shadowView.getLeft();
left = right - shadowWidth;
}
shadowDrawable.setBounds(left, top, right, bottom);
shadowDrawable.draw(c);
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels; //圆角
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); //Mode.SRC_IN 用前面画的“圆角矩形”对bitmap进行裁剪。
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public void drawSelector(View content, Canvas canvas, float openPercent) {
if (!mSelectorEnabled) return;
if (mSelectorDrawable != null && mSelectedView != null) {
String tag = (String) mSelectedView.getTag(R.id.selected_view);
if (tag.equals(TAG+"SelectedView")) {
canvas.save();
int left, right, offset;
offset = (int) (mSelectorDrawable.getWidth() * openPercent);
if (mMode == SlidingMenu.LEFT) {
right = content.getLeft();
left = right - offset;
canvas.clipRect(left, 0, right, getHeight());
canvas.drawBitmap(mSelectorDrawable, left, getSelectorTop(), null);
} else if (mMode == SlidingMenu.RIGHT) {
left = content.getRight();
right = left + offset;
canvas.clipRect(left, 0, right, getHeight());
canvas.drawBitmap(mSelectorDrawable, right - mSelectorDrawable.getWidth(), getSelectorTop(), null);
}
canvas.restore();
}
}
}
/**
* Draw the {@link Bitmap} of the drawable which indicated filled and empty
* passcode digits
*
* @param canvas - {@link Canvas} on which the drawable should be drawn
*/
private void drawDigitDrawable(Canvas canvas) {
paint.setAlpha(255);
int x = drawableStartX, y = drawableStartY;
int totalContentWidth = drawableWidth + digitHorizontalPadding;
for (int i = 1; i <= filledCount; i++) {
canvas.drawBitmap(filledDrawable, x, y, paint);
x += totalContentWidth;
}
for (int i = 1; i <= (digits - filledCount); i++) {
canvas.drawBitmap(emptyDrawable, x, y, paint);
x += totalContentWidth;
}
}
public CanvasTransformer zoom(final int openedX, final int closedX,
final int openedY, final int closedY,
final int px, final int py, final Interpolator interp) {
initTransformer();
mTrans = new CanvasTransformer() {
public void transformCanvas(Canvas canvas, float percentOpen) {
mTrans.transformCanvas(canvas, percentOpen);
float f = interp.getInterpolation(percentOpen);
canvas.scale((openedX - closedX) * f + closedX,
(openedY - closedY) * f + closedY, px, py);
}
};
return mTrans;
}
public void render(PointUtil p, int radius, Canvas canvas) {
if (this.radius <= radius) {
this.radius += growFactor; // / 10;
} else {
isFinished = true;
}
this.draw(p, canvas);
}
@NonNull
public static Bitmap getCircularBitmap(@NonNull Bitmap bitmap) {
Preconditions.nonNull(bitmap);
final Bitmap croppedCircularImg = Bitmap.createBitmap(
bitmap.getWidth(),
bitmap.getHeight(),
Bitmap.Config.ARGB_8888
);
final Canvas canvas = new Canvas(croppedCircularImg);
final Paint paint = new Paint();
final Rect rectangle = new Rect(
0,
0,
bitmap.getWidth(),
bitmap.getHeight()
);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(0xff424242);
canvas.drawOval(new RectF(rectangle), paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rectangle, rectangle, paint);
return croppedCircularImg;
}
@Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
public Bitmap getBitmapByView(View v)
{
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
return bitmap;
}
@Override
public synchronized void draw(final Canvas canvas) {
super.draw(canvas);
if(callback != null) {
callback.drawCallback(canvas);
}
}
@Override
public void draw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.draw(canvas);
}
}