下面列出了怎么用android.graphics.Paint的API类实例代码及写法,或者点击链接到github查看源代码。
private static String getEllipsizedText(Paint paint, String title, float maxWidth) {
final float textWidth = paint.measureText(title);
if (textWidth <= maxWidth) {
return title;
}
// Find the maximum length with an ellipsis.
final float ellipsisWidth = paint.measureText(ELLIPSIS);
final int length = paint.breakText(title, true, (maxWidth - ellipsisWidth), null);
// Try to land on a word break.
// TODO: Use breaking iterator for better i18n support.
final int space = title.lastIndexOf(' ', length);
if (space > 0) {
return title.substring(0, space) + ELLIPSIS;
}
// Otherwise, cut off characters.
return title.substring(0, length) + ELLIPSIS;
}
public void initView(Context context) {
this.context = context;
checked = false;
tick = new Path();
paint = new Paint();
bounds = new RectF();
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
setChecked(!checked);
onCheckedChangeListener.onCheckedChanged(MaterialCheckbox.this, isChecked());
}
};
setOnClickListener(onClickListener);
}
@Override
public int getSize(final Paint paint, final CharSequence text, final int start,
final int end, final Paint.FontMetricsInt fontMetrics) {
if (fontMetrics != null) {
final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
final float fontHeight = paintFontMetrics.descent - paintFontMetrics.ascent;
final float centerY = paintFontMetrics.ascent + fontHeight / 2;
fontMetrics.ascent = (int) (centerY - mEmoticonSize / 2);
fontMetrics.top = fontMetrics.ascent;
fontMetrics.bottom = (int) (centerY + mEmoticonSize / 2);
fontMetrics.descent = fontMetrics.bottom;
}
return (int) mEmoticonSize;
}
public MetronomeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
accentPaint = new Paint();
accentPaint.setStyle(Paint.Style.STROKE);
accentPaint.setStrokeWidth(8);
accentPaint.setAntiAlias(true);
accentPaint.setColor(Color.BLACK);
subscribe();
}
/**
* @param context
* used to get the configuration for the drawable from
*/
public DrawerArrowDrawable(Context context) {
final TypedArray typedArray = context.getTheme().obtainStyledAttributes(null,
R.styleable.DrawerArrowToggle, R.attr.drawerArrowStyle,
R.style.Base_Widget_AppCompat_DrawerArrowToggle);
mPaint.setAntiAlias(true);
mPaint.setColor(typedArray.getColor(R.styleable.DrawerArrowToggle_color, 0));
mSize = typedArray.getDimensionPixelSize(R.styleable.DrawerArrowToggle_drawableSize, 0);
mBarSize =0;// typedArray.getDimension(R.styleable.DrawerArrowToggle_barSize, 0);
mTopBottomArrowSize = //typedArray.getDimension(R.styleable.DrawerArrowToggle_topBottomBarArrowSize, 0);
mBarThickness = typedArray.getDimension(R.styleable.DrawerArrowToggle_thickness, 0);
mBarGap = typedArray.getDimension(R.styleable.DrawerArrowToggle_gapBetweenBars, 0);
mSpin = typedArray.getBoolean(R.styleable.DrawerArrowToggle_spinBars, true);
mMiddleArrowSize =0;// typedArray.getDimension(R.styleable.DrawerArrowToggle_middleBarArrowSize, 0);
typedArray.recycle();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setStrokeWidth(mBarThickness);
}
/**
* Calculate views bounds and scroll them according to the current index
*
* @param paint
* @return
*/
private ArrayList<Rect> calculateAllBounds(Paint paint) {
ArrayList<Rect> list = new ArrayList<Rect>();
//For each views (If no values then add a fake one)
final int count = InfiniteViewPager.FakePositionHelper.getAdapterSize(mViewPager);
final int width = getWidth();
final int halfWidth = width / 2;
for (int i = 0; i < count; i++) {
Rect bounds = calcBounds(i, paint);
int w = bounds.right - bounds.left;
int h = bounds.bottom - bounds.top;
bounds.left = (int)(halfWidth - (w / 2f) + ((i - mCurrentPage - mPageOffset) * width));
bounds.right = bounds.left + w;
bounds.top = 0;
bounds.bottom = h;
list.add(bounds);
}
return list;
}
/**
*/
private void setupTargetBitmap(int alpha) {
if (mBitmap == null) {
mBitmap = textAsBitmap("-");
}
if (mIconBitmap == null) {
mIconBitmap = textAsBitmap("-");
}
mBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Config.ARGB_8888);
Canvas mCanvas = new Canvas(mBitmap);
Paint mPaint = new Paint();
mPaint.setColor(mIconColor);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setAlpha(alpha);
mCanvas.drawRect(mIconRect, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mPaint.setAlpha(255);
mCanvas.drawBitmap(mIconBitmap, null, mIconRect, mPaint);
}
public PaperProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.PaperProgressBar, defStyleAttr, 0);
try {
mProgressColor = a.getColor(R.styleable.PaperProgressBar_pw_progressColor, 0xFF0F9D58);
// Secondary progress by default is same color, but half transparent
mSecondaryProgressColor = a.getColor(R.styleable.PaperProgressBar_pw_secondaryProgressColor,
0x7F000000 | (mProgressColor & 0xFFFFFF));
} finally {
a.recycle();
}
mColorPaint.setColor(mProgressColor);
mColorPaint.setStyle(Paint.Style.FILL);
mColorPaint.setAntiAlias(true);
mIndeterminateProgress = 0;
if (isIndeterminate()) {
mIndeterminateHandler.sendEmptyMessage(0);
}
}
private void initConfig() {
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
String testText = "菜单选项";
Rect rect = new Rect();
textPaint.getTextBounds(testText, 0, testText.length(), rect);
itemHeight = rect.height() + itemVerticalSpace;
textBaseLine = -itemHeight / 2.0f + (itemHeight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
if (showCount < 5) {
showCount = 5;
}
if (showCount % 2 == 0) {
showCount++;
}
drawCount = showCount + 2;
defaultRectArray = new Rect[drawCount];
drawRectArray = new Rect[drawCount];
for (int i = 0; i < drawCount; i++) {
defaultRectArray[i] = new Rect();
drawRectArray[i] = new Rect();
}
}
private void dimChildView(View v, float mag, int fadeColor) {
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (mag > 0 && fadeColor != 0) {
final int baseAlpha = (fadeColor & 0xff000000) >>> 24;
int imag = (int) (baseAlpha * mag);
int color = imag << 24 | (fadeColor & 0xffffff);
if (lp.dimPaint == null) {
lp.dimPaint = new Paint();
}
lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER));
if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_HARDWARE) {
ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_HARDWARE, lp.dimPaint);
}
invalidateChildRegion(v);
} else if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_NONE) {
if (lp.dimPaint != null) {
lp.dimPaint.setColorFilter(null);
}
final DisableLayerRunnable dlr = new DisableLayerRunnable(v);
mPostedRunnables.add(dlr);
ViewCompat.postOnAnimation(this, dlr);
}
}
public SketchShapeBitmapDrawable(@NonNull Context context, @NonNull BitmapDrawable bitmapDrawable, @Nullable ShapeSize shapeSize, @Nullable ImageShaper shaper) {
Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap == null || bitmap.isRecycled()) {
throw new IllegalArgumentException(bitmap == null ? "bitmap is null" : "bitmap recycled");
}
if (shapeSize == null && shaper == null) {
throw new IllegalArgumentException("shapeSize is null and shapeImage is null");
}
this.bitmapDrawable = bitmapDrawable;
this.paint = new Paint(DEFAULT_PAINT_FLAGS);
this.srcRect = new Rect();
this.resizeCalculator = Sketch.with(context).getConfiguration().getResizeCalculator();
setShapeSize(shapeSize);
setShaper(shaper);
if (bitmapDrawable instanceof SketchRefDrawable) {
this.refDrawable = (SketchRefDrawable) bitmapDrawable;
}
if (bitmapDrawable instanceof SketchDrawable) {
this.sketchDrawable = (SketchDrawable) bitmapDrawable;
}
}
public void addNowLine(long now) {
LineGraphSeries<DataPoint> seriesNow;
DataPoint[] nowPoints = new DataPoint[]{
new DataPoint(now, 0),
new DataPoint(now, maxY)
};
seriesNow = new LineGraphSeries<>(nowPoints);
seriesNow.setDrawDataPoints(false);
// custom paint to make a dotted line
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
paint.setColor(Color.WHITE);
seriesNow.setCustomPaint(paint);
addSeries(seriesNow);
}
/**
* Do not support cross Span.
*
* @param text text
* @param parentSpan parentSpan
* @param start start index of parentSpan
* @param end end index of parentSpan
* @param paint TextPaint
* @return recursive calculated width
*/
public int recursiveGetSizeWithReplacementSpan(CharSequence text, ReplacementSpan parentSpan, @IntRange(from = 0) int start, @IntRange(from = 0) int end, Paint paint) {
if (text instanceof Spanned) {
Spanned spannedText = (Spanned) text;
List<ReplacementSpan> spans = getSortedReplacementSpans(spannedText, start, end);
if (!spans.isEmpty()) {
int lastIndexCursor = 0;
int width = 0;
for (ReplacementSpan span : spans) {
if (span == parentSpan) {
continue;
}
int spanStart = spannedText.getSpanStart(span);
int spanEnd = spannedText.getSpanEnd(span);
width += parentSpan.getSize(paint, text, lastIndexCursor, spanStart, null);
width += span.getSize(paint, text, spanStart, spanEnd, null);
lastIndexCursor = spanEnd;
}
if (lastIndexCursor < end) {
width += parentSpan.getSize(paint, text, lastIndexCursor, end, null);
}
return width;
}
}
return parentSpan.getSize(paint, text, start, end, null);
}
public void init() {
mFramesCouner = 0;
mFrequency = Core.getTickFrequency();
mprevFrameTime = Core.getTickCount();
mStrfps = "";
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setTextSize(20);
}
/*********************************************************
* Painting
*********************************************************/
@Override
protected void onDraw(Canvas can)
{
rect.set(getPaddingLeft(), getPaddingTop(), this.getRight() - this.getLeft() - getPaddingRight(),
this.getBottom() - this.getTop() - getPaddingBottom());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(0);
paint.setAntiAlias(true);
if (isHorizontal)
{
drawHorizontalBar(can, paint);
}
else
{
drawVerticalBar(can, paint);
}
if (function != null && function.getMinMaxValues(FunctionIf.Z) != null)
{
drawLabels(can, paint, function.getMinMaxValues(FunctionIf.Z));
}
// Test code to trace paddings:
// paint.setStyle(Paint.Style.STROKE);
// paint.setStrokeWidth(0);
// paint.setColor(Color.BLUE);
// can.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
// paint.setColor(Color.GREEN);
// can.drawRect(getPaddingLeft(), getPaddingTop(), this.getRight() - this.getLeft() - getPaddingRight(),
// this.getBottom() - this.getTop() - getPaddingBottom(), paint);
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
// mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
// mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
protected void initializePaints() {
arcPaint = new Paint();
arcPaint.setAntiAlias(true);
arcPaint.setStyle(Paint.Style.STROKE);
arcPaint.setStrokeWidth(arcWidth);
arcPaint.setColor(BLUE_ONE);
arrowPaint = new Paint();
arrowPaint.setAntiAlias(true);
arrowPaint.setStyle(Paint.Style.STROKE);
arrowPaint.setStrokeWidth(arrowWidth);
arrowPaint.setColor(WHILE);
smallPaint = new Paint();
smallPaint.setAntiAlias(true);
smallPaint.setStyle(Paint.Style.FILL);
smallPaint.setColor(WHILE);
triPaint = new Paint();
triPaint.setAntiAlias(true);
triPaint.setStyle(Paint.Style.STROKE);
triPaint.setStrokeWidth(triWidth);
triPaint.setColor(WHILE);
loadingPaint = new Paint();
loadingPaint.setAntiAlias(true);
loadingPaint.setStyle(Paint.Style.STROKE);
loadingPaint.setStrokeWidth(loadingWidth);
loadingPaint.setColor(WHILE);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setStrokeWidth(1);
textPaint.setColor(WHILE);
textPaint.setTextSize(textSize);
}
public PopupBackground(Context context)
{
Resources res = context.getResources();
mCorner = res.getDimensionPixelSize(R.dimen.person_bubble_corner);
mPaint.setColor(res.getColor(R.color.person_bubble_bg));
mPaint.setStyle(Paint.Style.FILL);
}
@NonNull
private void removeAll(Canvas canvas) {
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
}
/**
* 绘制焦点框
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (Style.RECTANGLE == mStyle) {
mFocusPath.addRect(mFocusRect, Path.Direction.CCW);
canvas.save();
canvas.clipRect(0, 0, getWidth(), getHeight());
canvas.clipPath(mFocusPath, Region.Op.DIFFERENCE);
canvas.drawColor(mMaskColor);
canvas.restore();
} else if (Style.CIRCLE == mStyle) {
float radius = Math.min((mFocusRect.right - mFocusRect.left) / 2, (mFocusRect.bottom - mFocusRect.top) / 2);
mFocusPath.addCircle(mFocusMidPoint.x, mFocusMidPoint.y, radius, Path.Direction.CCW);
canvas.save();
canvas.clipRect(0, 0, getWidth(), getHeight());
canvas.clipPath(mFocusPath, Region.Op.DIFFERENCE);
canvas.drawColor(mMaskColor);
canvas.restore();
}
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBorderPaint.setAntiAlias(true);
canvas.drawPath(mFocusPath, mBorderPaint);
mFocusPath.reset();
}
private Drawable createOuterStrokeDrawable(float strokeWidth) {
ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
final Paint paint = shapeDrawable.getPaint();
paint.setAntiAlias(true);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Style.STROKE);
paint.setColor(Color.BLACK);
paint.setAlpha(opacityToAlpha(0.02f));
return shapeDrawable;
}
@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.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888;
Bitmap bitmap = Bitmap.createBitmap(size, size, config);
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;
}
/**
* Creates a rounded square of a certain color with
* a character imprinted in white on it.
*
* @param character the character to write on the image.
* @param width the width of the final image.
* @param height the height of the final image.
* @param color the background color of the rounded square.
* @return a valid bitmap of a rounded square with a character on it.
*/
@NonNull
public static Bitmap getRoundedLetterImage(@NonNull Character character, int width, int height, int color) {
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(color);
Typeface boldText = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
paint.setTypeface(boldText);
paint.setTextSize(Utils.dpToPx(14));
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
int radius = Utils.dpToPx(2);
RectF outer = new RectF(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.drawRoundRect(outer, radius, radius, paint);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
paint.setColor(Color.WHITE);
canvas.drawText(character.toString(), xPos, yPos, paint);
return image;
}
public OverlayView(final Context context, final AttributeSet attrs) {
super(context, attrs);
textSizePx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
fgPaint = new Paint();
fgPaint.setTextSize(textSizePx);
fgPaint.setColor(ContextCompat.getColor(context, R.color.textColorPrimary));
bgPaint = new Paint();
bgPaint.setColor(Color.TRANSPARENT);
}
private void init() {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mCircleColor = ViewUtils.getDefaultColor(getContext());
mIsMask = true;
}
private static void drawCircle(Paint st, Canvas g2, float x, float y) {
st.setColor(blue);
g2.translate(x, y);
g2.drawCircle(0, 0, 8, st);
st.setColor(Color.BLACK);
st.setStyle(Style.STROKE);
g2.drawCircle(0, 0, 8, st);
g2.translate(-x, -y);
}
@Override
protected Path getPath(Canvas canvas, Paint paint) {
Path path = new Path();
float x1 = ParserHelper.fromPercentageToFloat(mX1, mCanvasWidth, 0, mScale);
float y1 = ParserHelper.fromPercentageToFloat(mY1, mCanvasHeight, 0, mScale);
float x2 = ParserHelper.fromPercentageToFloat(mX2, mCanvasWidth, 0, mScale);
float y2 = ParserHelper.fromPercentageToFloat(mY2, mCanvasHeight, 0, mScale);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
return path;
}
private Paint getRipplePaint() {
try {
Method method = RippleDrawable.class.getDeclaredMethod("getRipplePaint");
method.setAccessible(true);
return (Paint) method.invoke(this);
} catch (NoSuchMethodException
| InvocationTargetException
| IllegalAccessException ignored) {
}
// Normally should never happen.
return new Paint();
}
RoundRectDrawableWithShadow(Resources resources, int backgroundColor, float radius) {
mShadowStartColor = resources.getColor(R.color.cardview_shadow_start_color);
mShadowEndColor = resources.getColor(R.color.cardview_shadow_end_color);
mShadowSize = resources.getDimension(R.dimen.cardview_shadow_size) * SHADOW_MULTIPLIER;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mPaint.setColor(backgroundColor);
mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mCornerShadowPaint.setStyle(Paint.Style.FILL);
mCornerShadowPaint.setDither(true);
mCornerRadius = radius;
mPreShadowBounds = new RectF();
mEdgeShadowPaint = new Paint(mCornerShadowPaint);
}
@Override
public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {
Bitmap source = resource.get();
int size = Math.min(source.getWidth(), source.getHeight());
int width = (source.getWidth() - size) / 2;
int height = (source.getHeight() - size) / 2;
Bitmap bitmap = mBitmapPool.get(size, size, Bitmap.Config.ARGB_8888);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader =
new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
if (width != 0 || height != 0) {
// source isn't square, move viewport to center
Matrix matrix = new Matrix();
matrix.setTranslate(-width, -height);
shader.setLocalMatrix(matrix);
}
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return BitmapResource.obtain(bitmap, mBitmapPool);
}