在Android中创建一个自定义的View来绘制心形可以通过继承View类并重写其onDraw()方法来实现。

package com.example.customview;import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;public class HeartShapeView extends View {private Paint paint;private Path path;public HeartShapeView(Context context) {super(context);init();}public HeartShapeView(Context context, AttributeSet attrs) {super(context, attrs);init();}public HeartShapeView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init();}private void init() {paint = new Paint();paint.setColor(Color.RED);paint.setStyle(Paint.Style.FILL);paint.setAntiAlias(true);path = new Path();}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);drawHeartPath(w, h);}private void drawHeartPath(int width, int height) {float centerX = width / 2f;float centerY = height / 2f;float radius = Math.min(width, height) * 0.35f;path.reset();path.moveTo(centerX, centerY - radius);path.cubicTo(centerX + radius/2, centerY - radius*1.5f,centerX + radius*1.5f, centerY - radius/2,centerX + radius, centerY);path.cubicTo(centerX + radius*0.75f, centerY + radius/4,centerX - radius*0.75f, centerY + radius/4,centerX - radius, centerY);path.cubicTo(centerX - radius*1.5f, centerY - radius/2,centerX - radius/2, centerY - radius*1.5f,centerX, centerY - radius);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);canvas.drawPath(path, paint);}
}

布局XML文件中使用这个自定义的HeartShapeView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><com.example.customview.HeartShapeViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"/>
</RelativeLayout>